I want to compare two Java objects without overriding equals method. Since I need to override equals method in n number of Classes I have, I am in need of a common utility method where we can compare two Java objects.
Something like:
A a1,a2;
B b1,b2;
C c1,c2;
-----
-----
boolean isEqual1 = new ObjectComparator().isEquals(a1 , a2);
boolean isEqual2 = new ObjectComparator().isEquals(b1 , b2);
boolean isEqual3 = new ObjectComparator().isEquals(c1 , c2);
Please help me out to write a common utility for comparing any Java objects
Hope by using Field
class, and getClass
method we can achieve it. Please guide me.
Have a look at EqualsBuilder.reflectionEquals
in the Apache Commons library.
From the documentation:
This method uses reflection to determine if the two Objects are equal.
It uses
AccessibleObject.setAccessible
to gain access to private fields. This means that it will throw a security exception if run under a security manager, if the permissions are not set up correctly. It is also not as efficient as testing explicitly.
So, in your example it would look like:
A a1,a2;
B b1,b2;
C c1,c2;
-----
-----
boolean isEqual1 = EqualsBuilder.reflectionEquals(a1 , a2);
boolean isEqual2 = EqualsBuilder.reflectionEquals(b1 , b2);
boolean isEqual3 = EqualsBuilder.reflectionEquals(c1 , c2);
This may be what you are looking for EqualsBuilder.reflectionEquals
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With