用于复杂对象的apache EqualsBuilder

时间:2013-12-16 04:05:56

标签: java unit-testing reflection comparison apache-commons

我试图比较具有复杂结构的两个对象,但是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;
    }
}

1 个答案:

答案 0 :(得分:1)

EqualsBuilder.reflectionEquals方法无法通过反射将相同的相等性测试应用于SecondLevel类字段。您需要在SecondLevel类中覆盖equals(因此hashCode)才能传递此内容。

如果你不能覆盖equals,并且很乐意为你的项目添加另一个依赖项,那么你也可以查看Unitils库中的ReflectionAssert.assertReflectionEquals方法:

http://www.unitils.org/apidocs/org/unitils/reflectionassert/ReflectionAssert.html