package com.haoyihang.test.invoke;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class CompareObj1 {
public static void main(String[] args) {
ObjectTest obj1=new ObjectTest("张三","1",null);
ObjectTest obj2=new ObjectTest("李四","11",null);
String[] ignoreArr= {"name","age","size"};
String result=compareFields(obj1,obj2,ignoreArr);
System.out.println(result);
}
public static String compareFields(Object obj1, Object obj2, String[] ignoreArr) {
try {
HashMap json = new HashMap();
List ignoreList = null;
if (ignoreArr != null && ignoreArr.length > 0) {
ignoreList = Arrays.asList(ignoreArr);
}
if (obj1 == null && obj2 == null) {
}
if (obj1 == null) {
HashMap json1 = new HashMap();
Class clazz = obj2.getClass();
//获取object的属性描述
PropertyDescriptor[] pds = Introspector.getBeanInfo(clazz, Object.class).getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
String name = pd.getName();
if (ignoreList != null && ignoreList.contains(name)) {
continue;
}
Method readMethod = pd.getReadMethod();//获取属性的get方法
//在obj2上调用get方法等同于获得obj2的属性值
Object o2 = readMethod.invoke(obj2);
//不一致
json1.put("变更后", o2);
json.put(name, json1);
continue;
}
return json.toString();
} else if (obj2 == null) {
HashMap json1 = new HashMap();
Class clazz = obj1.getClass();
//获取object的属性描述
PropertyDescriptor[] pds = Introspector.getBeanInfo(null, Object.class).getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
String name = pd.getName();
if (ignoreList != null && ignoreList.contains(name)) {
continue;
}
Method readMethod = pd.getReadMethod();//获取属性的get方法
//在obj1上调用get方法等同于获得obj1的属性值
Object o1 = readMethod.invoke(obj1);
//不一致
json1.put("变更前", o1);
json.put(name, json1);
continue;
}
return json.toString();
}
if (obj1.getClass() == obj2.getClass()) {
Class clazz = obj1.getClass();
//获取object的属性描述
Field[] fields = obj1.getClass().getDeclaredFields();//获得属性
for (Field field : fields) {
PropertyDescriptor pd = new PropertyDescriptor(field.getName(),clazz);
Method method = pd.getReadMethod();//获得get方法
String name = pd.getName();
//在obj1上调用get方法等同于获得obj1的属性值
Object o1 = method.invoke(obj1);
//在obj2上调用get方法等同于获得obj2的属性值
Object o2 = method.invoke(obj2);
if (o1 == null && o2 == null) {
continue;
}//比较时短路
if (o1 == null || o2 == null || !o1.equals(o2)) {
HashMap json1 = new HashMap();
json1.put("变更后", o2);
json1.put("变更前", o1);
json.put(name, json1);
}
}
return json.toString();
}
return json.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}