透過反射對比兩個物件是否相等

东峰叵,com發表於2024-07-02
/**
* 透過反射對比兩個物件是否相等
*
* @param obj1 obj1
* @param obj2 obj2
* @return boolean
* @throws IllegalAccessException e
*/
public static boolean propertiesAreEqual(Object obj1, Object obj2) throws IllegalAccessException {
if (obj1 == obj2) {
return true;
}
if (obj1 == null || obj2 == null) {
return false;
}
if (obj1.getClass() != obj2.getClass()) {
return false;
}
Field[] fields = obj1.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true); // 使私有屬性也可以訪問
Object val1 = field.get(obj1);
Object val2 = field.get(obj2);
if (!Objects.equals(val1, val2)) {
return false;
}
}
return true;
}

相關文章