比较对象

来源:互联网 发布:java项目名称命名规范 编辑:程序博客网 时间:2024/05/29 15:04

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;

}

}

原创粉丝点击