有時候我們需要對兩個對象的屬性值進行一些比較操作,例如在做一些保存操作時判斷是否有屬性被修改等。
那么你可以將以下代碼進行一些修改作為一個工具類來使用。
其中Pojo為你自己定義的對象類型,根據(jù)需求進行修改即可。
public static boolean contrastObj(Object obj1, Object obj2) {
boolean isEquals = true;
if (obj1 instanceof Pojo && obj2 instanceof Pojo ) {
Pojo pojo1 = (Pojo) obj1;
Pojo pojo2 = (Pojo) obj2;
List textList = new ArrayList<String>();
try {
Class clazz = pojo1.getClass();
Field[] fields = pojo1.getClass().getDeclaredFields();
for (Field field : fields) {
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
Method getMethod = pd.getReadMethod();
Object o1 = getMethod.invoke(pojo1);
Object o2 = getMethod.invoke(pojo2);
if (!o1.toString().equals(o2.toString())) {
isEquals = false;
textList.add(getMethod.getName() + ":" + "false");
} else {
textList.add(getMethod.getName() + ":" + "true");
}
}
} catch (Exception e) {
}
for (Object object : textList) {
System.out.println(object);
}
}
return isEquals;
}