package com.gildata.task.platform.common.util;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gildata.task.platform.common.operationLog.TaskPoolConfigLog;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
public class CompareUtil {
/**
* , boolean,true
*
* @param oldObject 1
* @param newObject 2
* @return boolean
*/
public static boolean isDiff(Object oldObject, Object newObject) {
JSONArray jsonArray = compareFields(oldObject, newObject, null);
if (jsonArray.size() > 0) {
return true;
} else {
return false;
}
}
/**
* , map key,value Map oldObject,newObject
*
* @param obj1 1
* @param obj2 2
* @param ignoreArr
* @return map
*/
@SuppressWarnings("rawtypes")
public static JSONArray compareFields(Object obj1, Object obj2, String[] ignoreArr) {
JSONArray jsonArray = new JSONArray();
try {
List ignoreList = null;
if (ignoreArr != null && ignoreArr.length > 0) {
// array list
ignoreList = Arrays.asList(ignoreArr);
}
if (obj1.getClass() == obj2.getClass()) {//
Class clazz = obj1.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
// obj1 get obj1
Object o1 = readMethod.invoke(obj1);
// obj2 get obj2
Object o2 = readMethod.invoke(obj2);
if (o1 instanceof Timestamp) {
o1 = new Date(((Timestamp) o1).getTime());
}
if (o2 instanceof Timestamp) {
o2 = new Date(((Timestamp) o2).getTime());
}
if (o1 == null && o2 == null) {
continue;
} else if ((o1 == null && o2 != null)) {
JSONObject map = new JSONObject();
map.put("fieldName", name);
map.put("oldValue", "");
map.put("newValue", o2);
jsonArray.add(map);
continue;
} else if ((o2 == null && o1 != null)) {
JSONObject map = new JSONObject();
map.put("fieldName", name);
map.put("oldValue", o1);
map.put("newValue", "");
jsonArray.add(map);
continue;
}
if (!o1.equals(o2)) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("fieldName", name);
jsonObject.put("oldValue", o1);
jsonObject.put("newValue", o2);
jsonArray.add(jsonObject);
}
}
}
return jsonArray;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
TaskPoolConfigLog taskPoolConfigLog1 = new TaskPoolConfigLog();
TaskPoolConfigLog taskPoolConfigLog2 = new TaskPoolConfigLog();
taskPoolConfigLog1.setAppCode("1");
taskPoolConfigLog2.setAppCode("2");
taskPoolConfigLog1.setName(" ");
taskPoolConfigLog2.setAppCode(" ");
taskPoolConfigLog2.setUpdateTime(new Date());
String[] ignoreArr = new String[3];
compareFields(taskPoolConfigLog1, taskPoolConfigLog2, ignoreArr);
}
}