toString 更优雅的实现方式

最后更新 : 2020.01.15  

看看xxx的写法,不是很优雅

@Override
	public String toString() {
		return "FillRecordDetailEntity [id=" + id + ", fillRecordTotalId="
				+ fillRecordTotalId + ", businessInfoId=" + businessInfoId
				+ ", commitTime=" + commitTime + ", lastUpdateTime="
				+ lastUpdateTime + ", isISubmit=" + isISubmit
				+ ", isFinalValid=" + isFinalValid 
				+ ", infoCode=" + infoCode 
				+ ", handlerResult=" + handlerResult
				+ ", checkStatus=" + checkStatus +
				//", scanFileRecordEntity="
				//+ scanFileRecordEntity + 
				", fieldVlaueEntitySet="
				+ fieldVlaueEntitySet + "]";
	}
	

要善于利用工具才可以提高效率,下面利用apache Commons Lang之toString()实现

  • 给出实体类
public class Foo { 
        private String name; 
        private int age; 
        private Bar bar; 

        public Foo(String name, int age) { 
                this.name = name; 
                this.age = age; 
        }

        //省略getter/setter方法 

}
  • 通过反射方式实现toString();
@Override 
        public String toString() { 
                return ReflectionToStringBuilder.toString(this); 
        }
  • 通过自定义格式方式实现

        @Override 
        public String toString() { 
                return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) 
                                .append("name", name) 
                                .append("age", age) 
                                .append("bar", bar) 
                                .toString(); 
        }
在这里插入图片描述

哪个更优化,更高效,一看便知

- END -

70
0