java compare objects: using reflection?

ぐ巨炮叔叔 提交于 2019-12-10 11:07:39

问题


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


回答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.




回答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.




回答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.




回答4:


The idea is interesting, but please be aware that reflection can be slow. If you need to do a lot of comparisons, or you are putting your objects in collection classes that do comparisons (for example HashMap, HashSet etc.) then comparing objects via reflection can become a performance bottleneck.



来源:https://stackoverflow.com/questions/1520941/java-compare-objects-using-reflection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!