Java compare objects: using reflection?
I have an object that itself has multiple objects as fields. The question I have is, I have two objects of this type, and I want to compare these two. I know I can do equals, comparators, etc., but is there a way to use reflection to get the properties of an object and do the comparison.
for example if I have a Car object which is like a wheel object which has a tire object which has bolts object. Remember that all the listed objects are separate and not nested classes. How to compare 2 cars?
Any help is appreciated?
thank
source to share
public class Car {
private Wheels wheels;
// other properties
public boolean equals(Object ob) {
if (!(ob instanceof Car)) return false;
Car other = (Car)ob;
// compare properties
if (!wheels.equals(other.wheels)) return false;
return true;
}
}
- the right approach. Automatic comparison via reflection is not recommended. On the one hand, "state" is a more general concept than reflected property mapping.
You could write something that did a deep reflection, but that didn't miss the point.
source to share
Apache Commons Lang has EqualsBuilder that does exactly that (see methods reflectionEquals()
)
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
EqualsBuilder
also provides more explicit methods for null-safe comparison of specific fields, making it a little less cumbersome to write the "correct" (that is, non-reflective) equivalent technique.
source to share
An interesting idea, but please remember that reflections can be slow. If you need to make a lot of comparisons, or do you put your items in the collection classes that perform the comparison (eg HashMap
, HashSet
etc.), the comparison of objects through the reflection can be a performance bottleneck.
source to share