反射操作对象的属性值和对象的方法
@SuppressWarnings("unchecked")
public class CompareObject {
public static <T> T compareTwoObjectToMap(T classBefore, T classAfter) {
Field[] declaredFields = classBefore.getClass().getDeclaredFields();
List<Field> list = Arrays.stream(declaredFields).filter(p -> !"serialVersionUID".equals(p.getName())).collect(Collectors.toList());
HashMap<String, Object> map = new HashMap<>();
list.forEach(p->{
PropertyDescriptor pd = null;
try {
pd = new PropertyDescriptor(p.getName(), classBefore.getClass());
} catch (IntrospectionException e) {
e.printStackTrace();
}
Method readMethod =null;
if (ObjectUtils.isNotEmpty(pd)) {
readMethod = pd.getReadMethod();
}
Object beforeClassValue = null;
try {
if (ObjectUtils.isNotEmpty(readMethod)) {
beforeClassValue = readMethod.invoke(classBefore);
}
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
Object afterClassValue = null;
try {
if (ObjectUtils.isNotEmpty(readMethod)) {
afterClassValue = readMethod.invoke(classAfter);
}
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
if (ObjectUtils.isEmpty(beforeClassValue) && ObjectUtils.isNotEmpty(afterClassValue)) {
map.put(p.getName(), afterClassValue);
}
if (ObjectUtils.isNotEmpty(beforeClassValue) && ObjectUtils.isEmpty(afterClassValue)) {
map.put(p.getName(), beforeClassValue);
}
if (ObjectUtils.isNotEmpty(beforeClassValue) && ObjectUtils.isNotEmpty(afterClassValue)) {
if (!beforeClassValue.equals(afterClassValue)) {
map.put(p.getName(), beforeClassValue);
}
}
});
return (T) JSON.parseObject(JSON.toJSONString(map), classBefore.getClass());
}
}