public class CompareObjByFields{
private static CompareObjByFields compareObjByFileds = null;
private CompareObjByFields(){}
public static synchronized CompareObjByFields newInstance(){ // 創建唯一的對象
if(compareObjByFileds == null){
compareObjFields = new CompareObjByFields();
}
return compareObjFields;
}
@SuppressWarnings({"unchecked"})
public boolean compareObj(Object obj1,Object obj2,String[] params) throws IllegalArgumentException{
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:deckaredFields1){
filedName = fieldObj1.getName();
type = fieldObj1.getType();
factType = type.toString();
factType = factType.substring(factType.indexOf(32)+1);
fieldObj1.setAccessible(true);
convert = fieldObj1.get(obj1);
value = conver.trt == 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 中都沒有則繼續比較
f(!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;
}
}