java 反射 记录修改前后的数据,精确到每个字段

效果
在这里插入图片描述

package com.lst.sys.zhangth;

import java.lang.reflect.Field;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class RecordProxy {

    private static final Logger LOGGER = LoggerFactory.getLogger(RecordProxy.class);

    public static void main(String[] args) {
        User u1 = new User(1L,"张三",16,"java");
        User u2 = new User(1L,"李四",18,"C++");
        addRecord(u1,u2);
    }

    public RecordProxy(){}


    /**
     * @param oldObj 原数据对象
     * @param newObj 修改后数据对象
     */
    public static void addRecord(Object oldObj, Object newObj){
        try {
            // 得到类对象
            Class<? extends Object> class1 = oldObj.getClass();
            Class<? extends Object> class2 = newObj.getClass();
            if(!class1.equals(class2)){
                throw new RuntimeException("请传入两个相同的实体类对象");
            }
            // 得到属性集合
            Field[] fields1 = class1.getDeclaredFields();
            Field[] fields2 = class2.getDeclaredFields();
            StringBuffer info = new StringBuffer();
            Long id = null;
            for (Field field1 : fields1) {
                field1.setAccessible(true);    // 设置属性是可以访问的(私有的也可以)
                if(id == null && field1.getName().equals("id")){
                    id = (Long)field1.get(oldObj);
                }
                for (Field field2 : fields2) {
                    field2.setAccessible(true);    // 设置属性是可以访问的(私有的也可以)
                    if(field1.equals(field2)){    // 比较属性名是否一样
                        if(field2.get(newObj) == null || StringUtils.isEmpty(field2.get(newObj) + "")){
                            break;    // 属性名称一样就退出二级循环
                        }
                        if(!field1.get(oldObj).equals(field2.get(newObj))){    // 比较属性值是否一样
                            // 得到注解
                            LogCompar pn = field1.getAnnotation(LogCompar.class);
                            if(pn != null){
                                info.append(pn.value() + ":\"" +  field1.get(oldObj) + "\" 改成 \"" + field2.get(newObj) + "\",");
                            }
                        }
                        break;    // 属性名称一样就退出二级循环
                    }
                }
            }
            if(info.length() != 0){
                // 设置日志信息
                System.out.println(info.length() == 0 ? info.toString() : info.substring(0, info.length() - 1));
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("属性内容更改前后验证错误,日志无法被记录!");
        }
    }

}

自定义注解

package com.lst.sys.zhangth;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface LogCompar {
    /**
     * 汉字全称
     * @return
     */
    String value();
}

比较变更的属性对象

package com.lst.sys.zhangth;

public class User {

    @LogCompar("ID")
    private Long id = null;

    @LogCompar("名称")
    private String name = null;

    @LogCompar("年龄")
    private Integer sax = null;

    @LogCompar("职业")
    private String job = null;

    public User(Long id, String name, Integer sax, String job) {
        this.id = id;
        this.name = name;
        this.sax = sax;
        this.job = job;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sax=" + sax +
                ", job='" + job + '\'' +
                '}';
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getSax() {
        return sax;
    }

    public void setSax(Integer sax) {
        this.sax = sax;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }
}

参考:https://www.cnblogs.com/hjieone/p/11586252.html


版权声明:本文为qq_32793985原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。