Wednesday, 8 October 2014

Compare two java objects deeply

Apche commons-lang package provides ‘EqualsBuilder‘ class. This class provides method ‘reflectionEquals’  to compare two objects for equality. Method ‘reflectionEquals’  is available in many variants. This method uses reflection to determine whether two Objects are equal.

public static boolean reflectionEquals(Object obj1, Object obj2, Collection<String> excludeFields)
public static boolean reflectionEquals(Object obj1, Object obj2, String[] excludeFields)
public static boolean reflectionEquals(Object obj1, Object obj2, boolean testTransients)
public static boolean reflectionEquals(Object obj1, Object obj2, boolean testTransients, Class<?> reflectUpToClass, String[] excludeFields)

Parameter
Description
obj1
Object1
to check for equality
obj2
Object2
to check for equality
testTransient
If
the TestTransients parameter is set to
true, transient members will be
tested, otherwise they are ignored
excludeFields
Array
of field names to exclude from testing
reflectUpToClass
Superclass
fields will be appended up to and including the specified superclass. A
  

Example
import org.apache.commons.lang3.builder.EqualsBuilder;

public class Marks {
    final int maths, physics, chemistry;

    Marks(int maths, int physics, int chemistry){
        this.maths = maths;
        this.physics = physics;
        this.chemistry = chemistry;
    }

     @Override
    public boolean equals(Object obj) {
        return EqualsBuilder.reflectionEquals(this, obj);
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 79 * hash + this.maths;
        hash = 79 * hash + this.physics;
        hash = 79 * hash + this.chemistry;
        return hash;
    }
}


import org.apache.commons.lang3.builder.EqualsBuilder;

public class Student {
    Marks marks;
    String firstName, lastName;
    final int id;

    Student(int id, String firstName, String lastName, Marks marks){
        this.firstName = firstName;
        this.lastName = lastName;
        this.marks = marks;
        this.id = id;
    }

    @Override
    public boolean equals(Object obj) {
        return EqualsBuilder.reflectionEquals(this, obj);
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 17 * hash + this.id;
        return hash;
    }

    /**
     *
     * @param args
     */
    public static void main(String args[]){
        Marks m1 = new Marks(95, 85, 75);
        Marks m2 = new Marks(95, 85, 75);
        Student s1 = new Student(1, "Hari", "Krishna", m1);
        Student s2 = new Student(1, "Hari", "Krishna", m2);

        System.out.println("Is s1 and s2 are equal "+s1.equals(s2));

        m1 = new Marks(95, 85, 75);
        m2 = new Marks(95, 85, 76);
        s2 = new Student(1, "Hari", "Krishna", m2);
        System.out.println("Is s1 and s2 are equal "+s1.equals(s2));
    }
}

Output
Is s1 and s2 are equal true
Is s1 and s2 are equal false

No comments:

Post a Comment