欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

toString 更优雅的实现方式

程序员文章站 2022-05-12 14:21:34
...

看看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(); 
        }

哪个更优化,更高效,一看便知
toString 更优雅的实现方式

相关标签: j2se