Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common method for comparing any two Java objects

Tags:

java

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.

like image 519
John Solomon Avatar asked Sep 07 '11 12:09

John Solomon


2 Answers

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);
like image 161
aioobe Avatar answered Nov 14 '22 23:11

aioobe


This may be what you are looking for EqualsBuilder.reflectionEquals

public boolean equals(Object obj) {
   return EqualsBuilder.reflectionEquals(this, obj);
}
like image 21
Peter Lawrey Avatar answered Nov 14 '22 23:11

Peter Lawrey