对象修改日志工具类


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"}
]
**/
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值