java compare objects: using reflection?

你说的曾经没有我的故事 提交于 2019-12-06 11:07:08
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.

skaffman

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.

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.

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.

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