java利用反射比较2个对象相关属性 (可以自定义比较属性)
import java.lang.reflect.Field;import java.util.HashMap;import java.util.Map;public class CompareObjByFileds {private static CompareObjByFileds compaeObjByFileds = null; private CompareObjByFileds() { } public static synchronized CompareObjByFileds newInstance() { if (compaeObjByFileds == null){ compaeObjByFileds = new CompareObjByFileds(); } return compaeObjByFileds; } @SuppressWarnings({"unchecked"}) public boolean compaeObj(Object obj1, Object obj2, String[] params) throws IllegalArgumentException, IllegalAccessException { // 如果params 为空则认为两个对象相等 if( params == null || params.length == 0) return true; Class classObj1 = obj1.getClass(); Class classObj2 = obj2.getClass(); //利用反射拿到相关属性 Field[] declaredFields1 = classObj1.getDeclaredFields(); Field[] declaredFields2 = classObj2.getDeclaredFields(); //实体属性名称String fieldName = null; Class type = null; //属性类型 String factType = null; String value = null; Object convert = null; Map<String, String[]> map1 = new HashMap<String, String[]>(); Map<String, String[]> map2 = new HashMap<String, String[]>(); //便利Obj1对象 拿到Obj1对象属性名和对应的值,并放到map中 for (Field fieldObj1 : declaredFields1) { fieldName = fieldObj1.getName(); type = fieldObj1.getType(); factType = type.toString(); factType = factType.substring(factType.indexOf(32) + 1); fieldObj1.setAccessible(true); convert = fieldObj1.get(obj1); value = convert == null ? null: convert.toString(); map1.put(fieldName, new String[]{factType, value}); } for (Field fieldObj2 : declaredFields2) { fieldName = fieldObj2.getName(); type = fieldObj2.getType(); factType = type.toString(); factType = factType.substring(factType.indexOf(32) + 1); fieldObj2.setAccessible(true); convert = fieldObj2.get(obj2); value = convert == null ? null: convert.toString(); map2.put(fieldName, new String[]{factType, value}); } String[] array1 = null, array2 = null; String type1 = null, type2 = null; String value1 = null, value2 = null; for (String string : params) { array1 = map1.get(string); array2 = map2.get(string); type1 = array1[0]; type2 = array2[0]; value1 = array1[1]; value2 = array2[1]; // params 中的字段,在obj1 和obj2 中都没有则继续比较 if(!map1.containsKey(string) && !map2.containsKey(string)) continue; // params 中的字段,在obj1 和obj2 中一个有一个没有则两对象不相等 if(!(map1.containsKey(string) && map2.containsKey(string))) return false; // params 中的字段,在obj1 和obj2 中值一个为空一个不为空且则两对象不相等 if((value1 == null && value2 != null) || (value1 != null && value2 == null)) return false; // params 中的字段,在obj1 和obj2 中值不为空且不等则两对象不相等 if(value1 != null && value2 != null && !value1.equals(value2)) return false; // params 中的字段,在obj1 和obj2 中值均空则两对象不相等 if(value1 == null && value2 == null) return true; } return true; }}}}}
?