比较任意两个对象,这两个对象可能类不同。
如果老对象为空,新对象不为空,则返回新对象所有的属性名和值的map对象和 "type": "add"
如果老对象不为空,新对象为空,则返回 "type": "delete"
如果新老对象不为空,则比对两个对象中,相同的属性,如果值不同, 则返回新对象的属性名和属性值和 "type": "update"的map对象。
-
- * Compare two object, and return new object diff key & value
- *
- * @param oldObject old object
- * @param newObject new object
- * @return Map key-value of new object if value not equals
- */
- @SuppressWarnings("rawtypes")
- public static Map<String, Object> diffObject(Object oldObject, Object newObject) {
- Map<String, Object> map = new HashMap<>();
- if (oldObject == null && newObject == null) {
- return map;
- }
- if (oldObject == null) {
- map.put("type", "add");
- } else if (newObject == null) {
- map.put("type", "delete");
- return map;
- }
- try {
-
- PropertyDescriptor[] newProperties = Introspector.getBeanInfo(newObject.getClass(), Object.class).getPropertyDescriptors();
- PropertyDescriptor[] oldProperties = oldObject == null ? null : Introspector.getBeanInfo(oldObject.getClass(), Object.class).getPropertyDescriptors();
- for (PropertyDescriptor newPD : newProperties) {
- String name = newPD.getName();
- Object newValue = newPD.getReadMethod().invoke(newObject);
- if (newValue instanceof List) {
- continue;
- } else if (oldProperties == null) {
- map.put(name, newValue);
- continue;
- }
-
- PropertyDescriptor oldPD = Arrays.stream(oldProperties).filter(e -> e.getName().equals(name)).findFirst().get();
- if (oldPD == null) {
- continue;
- }
- Object oldValue = oldPD.getReadMethod().invoke(oldObject);
- if (oldValue instanceof List) {
- continue;
- }
- if (!ObjectUtils.nullSafeEquals(oldValue, newValue)) {
- map.put("type", "update");
- map.put(name, newValue);
- }
- }
- } catch (Exception e) {
- }
- return map;
- }