import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import io.swagger.annotations.ApiModelProperty;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class LogUtil<T> {
/**
* 对象比较器
* 比较结果eg:1、字段名称loginName,旧值:liu,新值:gu;2、字段名称address,旧值:hunan,新值:neimenggu
* @param oldBean
* @param newBean
* @return
*/
public String compareObject(T oldBean, T newBean) {
if(oldBean==null || newBean==null){
return "";
}
JSONArray jsonArray=new JSONArray();
try {
Class clazz = oldBean.getClass();
Field[] fields = oldBean.getClass().getDeclaredFields();
for (Field field : fields) {
ApiModelProperty apiModelProperty=field.getAnnotation(ApiModelProperty.class);
if(apiModelProperty==null){
continue;
}
PropertyDescriptor pd =null;
try{
pd = new PropertyDescriptor(field.getName(), clazz);
}catch (Exception e){
continue;
}
Method getMethod = pd.getReadMethod();
Object o1 = getMethod.invoke(oldBean);
Object o2 = getMethod.invoke(newBean);
if (!String.valueOf(o1).equals(String.valueOf(o2))) {
JSONObject json=new JSONObject();
json.put("name",field.getName());
String dictNotes=apiModelProperty==null?null:apiModelProperty.notes();
if(dictNotes!=null){
for (String dict:dictNotes.split(",") ) {
if(dict.startsWith(o1+".")){
o1=o1+"("+dict+")";
break;
}
}
for (String dict:dictNotes.split(",") ) {
if(dict.startsWith(o2+".")){
o2=o2+"("+dict+")";
break;
}
}
}
json.put("title",apiModelProperty==null?field.getName():apiModelProperty.value());
json.put("old",o1);
json.put("new",o2);
jsonArray.add(json);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return JSON.toJSONString( jsonArray, SerializerFeature.WriteMapNullValue);
}
public static void main(String[] args) {
A a=new A();
a.setTitle("这里是标题");
a.setAccountId("111");
a.setBeginDate("2021-1-9");
a.setLoginUserId("123456789");
A b=new A();
b.setTitle("哈哈哈");
b.setAccountId("69658965");
b.setBeginDate("2021-9-18");
b.setLoginUserId("666");
String r = new LogUtil<A>().compareObject(a,b);
System.out.println(r);
/**
* [
{"new":"2021-9-18","old":"2021-1-9","name":"beginDate","title":"开始日期2021-07-26"},
{"new":"哈哈哈","old":"这里是标题","name":"title","title":"主题"},
{"new":"666","old":"123456789","name":"loginUserId","title":null},
{"new":"69658965","old":"111","name":"accountId","title":"员工id"}
]
**/
}
}
对象修改日志工具类
最新推荐文章于 2024-07-25 13:40:37 发布