java实现修改字段记录

1.写个注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Compare {
    String value();
}

2.工具类

public class ObjectComparator {

    public static List<Map<String, String>> compare(Object oldObj, Object newObj) {

        List<Map<String,String>> resultList= new ArrayList<>();
        try {
            // 获取所有字段
            Field[] fields = oldObj.getClass().getDeclaredFields();

            // 遍历所有字段
            for (Field field : fields) {
                // 如果字段被 @Compare 注解标注
                if (field.isAnnotationPresent(Compare.class)) {
                    // 获取字段的中文名
                    String fieldName = field.getAnnotation(Compare.class).value();

                    // 设置字段可访问
                    field.setAccessible(true);

                    // 获取字段的旧值和新值
                    Object oldValue = field.get(oldObj);
                    Object newValue = field.get(newObj);

                    // 如果值不相等
                    if (!Objects.equals(oldValue, newValue)) {
                        Map<String, String> result = new HashMap<>(16);
                        // 将字段名和值添加到结果中
                        result.put(fieldName, "旧值:" + oldValue + ",新值:" + newValue);
                        resultList.add(result);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return resultList;
    }

3.实体类

@Data
public class UserInfo {

    @Compare("姓名")
    private String name;

    @Compare("性别")
    private String sex;
}

4.测试

public class Test {

    public static void main(String[] args) {

       UserInfo oldUser = new UserInfo();
       oldUser.setName("张三");
       oldUser.setSex("男");

       UserInfo newUser = new UserInfo();
       newUser.setName("李四");
       newUser.setSex("女");
       List<Map<String, String>> changes = ObjectComparator.compare(oldUser, newUser);
        for(int i=0;i<changes.size();i++){
            Map<String,String> map = changes.get(i);
            for (Map.Entry<String, String> entry : map.entrySet()) {
                System.out.println(entry.getKey() + ":" + entry.getValue());
            }
        }

    }
}

5.结果
java实现修改字段记录_第1张图片

你可能感兴趣的:(java,开发语言,jvm)