比较 Java 中不同类对象的同名字段

  • 本文关键字:字段 对象 同类 Java 比较 java
  • 更新时间 :
  • 英文 :


我有两个对象,每个对象都有数十个字段:

Class1 {
int firstProperty;
String secondProperty;
String anotherProperty1;
...
}
Class2 {
int firstProperty;
String secondProperty;
String anotherProperty2;
...
}

有些方法名称完全相同,有些则不相同,例如在这里,它们都有firstPropertysecondProperty并且它们在名称上是相同的。 但其他字段则不同。知道两个类的两个对象的每个相同字段的值是否实际上相同,这是一种优雅的方法吗?

_________________________________更新_____________________________________

我仍然不确定为什么有些人仍然认为这正是重复的问题。由于问题已关闭,我必须在此处粘贴我的解决方案。

private boolean hasChanged(Object o1, Object o2){
if (o1 == null || o2 == null) {
return true;
}
Class clazz1 = o1.getClass();
Class clazz2 = o2.getClass();
for (Method method1 : clazz1.getDeclaredMethods()) {
for (Method method2 : clazz2.getDeclaredMethods()) {
try {
if (method1.getName().startsWith("get") && method1.getName().equals(method2.getName())) {
if (method1.invoke(o1, null) == null && method2.invoke(o2, null) == null) {
continue;
} else if (method1.invoke(o1, null) == null || method2.invoke(o2, null) == null) {
continue;
} else if (!method1.invoke(o1, null).equals(method2.invoke(o2, null))) {
return true;
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
return false;
}

我认为最好的方法是创建一个公共抽象类,它们都继承了一个覆盖的equals。像这样:

public abstract class ParentClass {
int firstProperty;
String secondProperty;
String anotherProperty1;
@Override
public boolean equals(ParentClass other)  {
return this.firstProperty == other.firstProperty &&
this.secondProperty.equals(other.secondProperty) &&
this.anotherProperty1.equals(other.anotherProperty1);
}
} 

然后就Class1 extends ParentClassClass2 extends ParentClass.然后,如果你有一个类 1 的实例,假设:Class1 a = new Class1();Class2 b = new Class2();你可以做a.equals(b)来比较相等性。

最新更新