我试图比较具有复杂结构的两个对象,但是apache EqualsBuilder.reflectionEquals无法比较这两个。你能告诉我我错过了什么吗?它返回false作为结果。
import org.apache.commons.lang.builder.EqualsBuilder;
public class Test {
public static void main(String[] args){
FirstLevel firstLevel1 = new FirstLevel("string1", "string2", new SecondLevel("line1"));
FirstLevel firstLevel12 = new FirstLevel("string1", "string2", new SecondLevel("line1"));
System.out.print(EqualsBuilder.reflectionEquals(firstLevel1, firstLevel12, true));
}
}
class FirstLevel{
String line1;
String line2;
SecondLevel secondLevel;
FirstLevel(String line1, String line2, SecondLevel secondLevel) {
this.line1 = line1;
this.line2 = line2;
this.secondLevel = secondLevel;
}
}
class SecondLevel{
String level2Line1;
SecondLevel(String level2Line1) {
this.level2Line1 = level2Line1;
}
}
答案 0 :(得分:1)
EqualsBuilder.reflectionEquals
方法无法通过反射将相同的相等性测试应用于SecondLevel类字段。您需要在SecondLevel类中覆盖equals
(因此hashCode
)才能传递此内容。
如果你不能覆盖equals,并且很乐意为你的项目添加另一个依赖项,那么你也可以查看Unitils库中的ReflectionAssert.assertReflectionEquals
方法:
http://www.unitils.org/apidocs/org/unitils/reflectionassert/ReflectionAssert.html