public static Map<String, CompareDTO> compareFields(Object source, Object target, List<String> comparedPropertyList) {
try {
Map<String, CompareDTO> map = Maps.newHashMap();
if (CollectionUtils.isEmpty(comparedPropertyList)) {
return null;
}
if (source == null || target == null) {
throw new BizException("source or target is null");
}
// 只有两个对象都是同一类型的才有可比性
if (source.getClass() != target.getClass()) {
throw new BizException("incompatible type");
}
Class clazz = source.getClass();
// 获取object的属性描述
PropertyDescriptor[] pds = Introspector.getBeanInfo(clazz, Object.class).getPropertyDescriptors();
// 这里就是所有的属性了
for (PropertyDescriptor pd : pds) {
// 属性名
String name = pd.getName();
// 如果不需要比较,跳到下一次循环
if (!comparedPropertyList.contains(name)) {
continue;
}
// get方法
Method readMethod = pd.getReadMethod();
// 在obj1上调用get方法等同于获得obj1的属性值
Object o1 = readMethod.invoke(source);
// 在obj2上调用get方法等同于获得obj2的属性值
Object o2 = readMethod.invoke(target);
if (o1 == null && o2 == null) {
continue;
} else if (o1 == null && o2 != null) {
CompareDTO compareDTO = new CompareDTO();
compareDTO.setOldValue(o1);
compareDTO.setNewValue(o2);
map.put(name, compareDTO);
continue;
}
// 比较这两个值是否相等,不等就可以放入map
if (!o1.equals(o2)) {
CompareDTO compareDTO = new CompareDTO();
compareDTO.setOldValue(o1);
compareDTO.setNewValue(o2);
map.put(name, compareDTO);
}
}
return map;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}