一、前言
通过apache的commons-lang包org.apache.commons.lang.builder.*路径下的ToStringBuilder.reflectionToString、EqualsBuilder.reflectionEquals、HashCodeBuilder.reflectionHashCode对toString()、equals、hashCode()对象方法进行重写,可以实现打印对象所有成员变量值、深度匹配对象相等(即使对象所有成员变量或hashCode相等,equals值false)、对象值相等情况hashCode对于同一个。
二、代码示例
package test;@b@@b@import org.apache.commons.lang.builder.*;@b@@b@public class BaseObject{@b@ @b@ private String siteName;@b@ private String siteAddress;@b@@b@ public BaseObject(String siteName,String siteAddress){@b@ this.siteName=siteName;@b@ this.siteAddress=siteAddress;@b@ }@b@@b@ public String toString()@b@ {@b@ return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);@b@ }@b@@b@ public boolean equals(Object o)@b@ {@b@ return EqualsBuilder.reflectionEquals(this, o);@b@ }@b@@b@ public int hashCode()@b@ {@b@ return HashCodeBuilder.reflectionHashCode(this);@b@ }@b@ @b@ public static void main(String[] args){@b@ @b@ BaseObject a=new BaseObject("小木人印象","http://www.xwood.net");@b@ BaseObject b=new BaseObject("小木人印象","http://www.xwood.net");@b@ System.out.println(a.toString());@b@ System.out.println(b.toString());@b@ @b@ System.out.println(a.hashCode());@b@ System.out.println(b.hashCode());@b@ @b@ System.out.println(b==a);@b@ @b@ }@b@}
控制台打印结果
test.BaseObject@1270b73[@b@ siteName=小木人印象@b@ siteAddress=http://www.xwood.net@b@]@b@test.BaseObject@8813f2[@b@ siteName=小木人印象@b@ siteAddress=http://www.xwood.net@b@]@b@911656430@b@911656430@b@false