Compare two entity attribute values, and return a map with the different attribute name as key, and value as a list to store the values of obj1 and obj2 respectively. The code is as follows:
package com.schdri.bimgis.disaster.domain.util; import cn.hutool.core.util.ObjectUtil; import org.springframework.stereotype.Component; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java. lang.reflect.Method; import java.math.BigDecimal; import java.sql.Timestamp; import java.util.*; @Component public class CompareFiledUtil { /** * Compare two entity attribute values and return a map to have differences The attribute name is key, and the value is a list to store the values of obj1 and obj2 respectively * * @param obj1 Object 1 for attribute comparison * @param obj2 Object 2 for attribute comparison * @param ignoreList Select the one that does not need to be compared Attribute name collection * @return Attribute difference comparison result map */ public static Map<String, List<Object>> compareFields(Object obj1, Object obj2, List<String> ignoreList) { try { Map<String, List<Object>> map = new HashMap<String, List<Object>>( ); // Only two objects of the same type can be compared if (obj1.getClass() == obj2.getClass()) { Class claz = obj1.getClass(); // Get the property description PropertyDescriptor of object [] pds = Introspector.getBeanInfo(claz, Object.class).getPropertyDescriptors(); // Here are all the properties for (PropertyDescriptor pd : pds) { // Property name String name = pd.getName();getName(); // If the current attribute chooses to ignore the comparison, skip to the next cycle if (ignoreList != null && ignoreList.contains(name)) { continue; } // get method Method readMethod = pd.getReadMethod(); // calling the get method on obj1 is equivalent to obtaining the property value of obj1 Object o1 = readMethod .invoke(obj1); // Calling the get method on obj2 is equivalent to obtaining the property value of 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 (o2 instanceof BigDecimal) { o2 = ((BigDecimal) o2).setScale(2, BigDecimal.ROUND_HALF_UP); } if ((ObjectUtil.isEmpty(o1) || o1.equals("null")) && (ObjectUtil.isEmpty(o2) || o2.equals("null"))) { continue; } if (o1 == null && o2 != null) { List list = new ArrayList(); list.add(o1); list.add(o2); map.put(name, list); continue; } // Compare whether these two values are equal, and if they are not equal, they can be put into the map if (!o1.equals(o2)) { List list = new ArrayList(); list.add(o1); list.add( o2); map.put(name, list); } } } return map; } catch (Exception e) { e.printStackTrace(); return null; } } }
The returned structure can modify the return type according to your own needs. .