/**
* 比较对象属性值不同
*
* @param obj1 进行属性比较的对象1
* @param obj2 进行属性比较的对象2
* @param ignoreArr 选择忽略比较的属性数组
* @return 属性差异比较结果 map
*/
@SuppressWarnings("rawtypes")
public static List<String> compareFields(Object obj1, Object obj2, String[] ignoreArr) {
try {
List<String> returnList = Lists.newArrayList();
List<String> ignoreList = null;
if (ignoreArr != null && ignoreArr.length > 0) {
ignoreList = Arrays.asList(ignoreArr);
}
if (obj1.getClass() == obj2.getClass()) { //只有两个对象都是同一类型才有可比性
Class clazz = obj1.getClass();
//获取object的属性描述
PropertyDescriptor[] pds = Introspector.getBeanInfo(clazz, Object.class).getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
String name = pd.getName();
if (ignoreList != null && ignoreList.contains(name)) {
continue;
}
Method readMethod = pd.getReadMethod();//获取属性的get方法
//在obj1上调用get方法等同于获得obj1的属性值
Object o1 = readMethod.invoke(obj1);
//在obj2上调用get方法等同于获得obj2的属性值
Object o2 = readMethod.invoke(obj2);
//如果此属性是时间
if (o1 instanceof Timestamp) {
o1 = new Date(((Timestamp) o1).getTime());
}
if (o2 instanceof Timestamp) {
o2 = new Date(((Timestamp) o2).getTime());
}
if (o1 == null && o2 == null) {
continue;
} else if (o1 == null && o2 != null) {
//不一致
returnList.add(String.valueOf(name));
continue;
}
if (!o1.equals(o2)) {
returnList.add(String.valueOf(name));
}
}
}
return returnList;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
比较两个对象哪些属性值不同,返回不同的属性
最新推荐文章于 2023-11-10 16:44:55 发布