对象比较器
* 比较结果eg:1、字段名称name,旧值:111,新值:222;2、字段名称address,旧值:222,新值:111,修改时间:2020-07-27 17:33:59
定义接口类
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author fj
* @version 1.0
* @date 2020/7/29 15:07
*/
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface OperateLogAnnotation {
String name() default "";
}
比较方法
package com.jkhh.provider.util;
import com.jkhh.common.core.support.UserHolder;
import com.jkhh.common.util.DateUtil;
import com.jkhh.provider.pojo.domain.project.Customer;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.stereotype.Component;
import javax.persistence.Column;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
/**
* @author fj
* @version 1.0
* @date 2020/7/27 17:23
*/
@Component
public class OperateLogUtil<T> {
/**
* 对象比较器
* 比较结果eg:1、字段名称name,旧值:111,新值:222;2、字段名称address,旧值:222,新值:111,修改时间:2020-07-27 17:33:59
* @param oldBean
* @param newBean
* @return
*/
public String compareObject(Object oldBean, Object newBean) {
String str = "";
T pojo1 = (T) oldBean;
T pojo2 = (T) newBean;
try {
Class clazz = pojo1.getClass();
Field[] fields = pojo1.getClass().getDeclaredFields();
int i = 1;
for (Field field : fields) {
if ("serialVersionUID".equals(field.getName())) {
continue;
}
String name = "";
//如果存在该注解
if(field.isAnnotationPresent(OperateLogAnnotation.class)){
OperateLogAnnotation dt = field.getAnnotation(OperateLogAnnotation.class);
System.out.println("DatabaseField="+dt.name());
name = dt.name();
}else{
name = field.getName();
}
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
Method getMethod = pd.getReadMethod();
Object o1 = getMethod.invoke(pojo1);
Object o2 = getMethod.invoke(pojo2);
if (o1 == null || o2 == null) {
continue;
}
if (!o1.toString().equals(o2.toString())) {
if (i != 1) {
str += ";";
}
str += i + " 修改了" + name + ":修改前:" + o1 + ",修改后:" + o2;
i++;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
public static void main(String[] args) {
Customer customer = new Customer();
customer.setName("111");
customer.setAddress("222");
Customer customer1 = new Customer();
customer1.setName("222");
customer1.setAddress("111");
OperateLogUtil logUtil = new OperateLogUtil();
String str = logUtil.compareObject(customer,customer1);
System.out.println(str);
}
}