Question

I am trying to compare two objects with complex structure but apache EqualsBuilder.reflectionEquals is failing to compare these two. Can you please tell me what i am missing. It returns false as result.

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;
    }
}
Was it helpful?

Solution

The EqualsBuilder.reflectionEquals method isn't able to apply the same test of equality via reflection to the SecondLevel class field. You will need to override equals (and therefore hashCode) in the SecondLevel class for this to pass.

If you can't override equals, and you are happy to add another dependency to your project then you could also look at the ReflectionAssert.assertReflectionEquals method in the Unitils library:

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top