/**标签:obj1,反射,obj2,return,Object,field,相等,getClass,对比 From: https://www.cnblogs.com/databank/p/18279775
* 通过反射对比两个对象是否相等
*
* @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;
}