java compare objects: using reflection?

12,467

Solution 1

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;
  }
}

is the correct approach. Automatic comparison via reflection is not recommended. For one thing "state" is a more generic concept than reflected property comparison.

You could write something that did deep reflection comparison but it's kinda missing the point.

Solution 2

Apache Commons Lang has an EqualsBuilder class that does exactly this (see the reflectionEquals() methods)

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

EqualsBuilder also provides more explicit methods for null-safe comparison of specific fields, which makes writing "proper" (i.e. non-reflective) equals methods a bit less onerous.

Solution 3

Most modern IDE's have generators for hashcode and equals which let you select the properties to take into account. Those beat performance of their reflective counterparts easily.

Share:
12,467
codeModuler
Author by

codeModuler

Updated on June 27, 2022

Comments

  • codeModuler
    codeModuler almost 2 years

    I have an object which itself has multiple objects as fields. The question I have is, I have two objects of these kind and I want to compare these two. I know I can do equals, comparator etc. but is there a way to use reflection to get the properties of the object and make comparison.

    for example, if I have a Car object, which as wheels object, which has tires object, which has bolts object. Please remember all the above objects are individual and not nested classes. How do I compare 2 car objects?

    Any help is appreciated?

    Thanks