使用Java反射机制获取获取两个对象同名属性内容不相同的列表
package test;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import test.vo.User;
public class CompareObjects {
/**
* 获取两个对象同名属性内容不相同的列表
* @param class1 对象1
* @param class2 对象2
* @return
* @throws ClassNotFoundException
* @throws IllegalAccessException
*/
public static List<Map<String ,Object>> compareTwoClass(Object class1,Object class2) throws ClassNotFoundException, IllegalAccessException {
List<Map<String,Object>> list=new ArrayList<Map<String, Object>>();
//获取对象的class
Class<?> clazz1 = class1.getClass();
Class<?> clazz2 = class2.getClass();
//获取对象的属性列表
Field[] field1 = clazz1.getDeclaredFields();
Field[] field2 = clazz2.getDeclaredFields();
//遍历属性列表field1
for(int i=0;i<field1.length;i++){
//遍历属性列表field2
for(int j=0;j<field2.length;j++){
//如果field1[i]属性名与field2[j]属性名内容相同
if(field1[i].getName().equals(field2[j].getName())){
if(field1[i].getName().equals(field2[j].getName())){
field1[i].setAccessible(true);
field2[j].setAccessible(true);
//如果field1[i]属性值与field2[j]属性值内容不相同
if (!compareTwo(field1[i].get(class1), field2[j].get(class2))){
Map<String,Object> map2=new HashMap<String, Object>();
map2.put("name",field1[i].getName());//不同属性名称
map2.put("old",field1[i].get(class1));
map2.put("new",field2[j].get(class2));
list.add(map2);
}
break;
}
}
}
}
return list;
}
/**
* 对比两个数据是否内容相同
*
* @param object1,object2
* @return boolean类型
*/
public static boolean compareTwo(Object object1,Object object2){
if(object1==null&&object2==null){
return true;
}
if(object1==null&&object2!=null){
return false;
}
if(object1.equals(object2)){
return true;
}
return false;
}
public static void main(String[] args) {
User user1=new User("周子玉", 17, 180);
User user2=new User("周子瑜", 18, 181);
try {
List<Map<String, Object>> diffrentList= compareTwoClass(user1,user2);
for (Map<String, Object> map : diffrentList) {
System.out.println(map);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}