以下是一个比较两个对象每个字段属性值不同的工具类,返回所有属性值不同的列名,如果有@ApiModelProperty注解的话返回其value值:

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import io.swagger.annotations.ApiModelProperty;

public class ObjectComparator {
    
    public static <T> List<String> compareObjects(T oldObject, T newObject) throws Exception {
        List<String> differentColumns = new ArrayList<>();

        // get all fields
        Field[] fields = oldObject.getClass().getDeclaredFields();

        for (Field field : fields) {
            field.setAccessible(true);
            Object oldValue = field.get(oldObject);
            Object newValue = field.get(newObject);

            // check if the field is annotated with ApiModelProperty
            ApiModelProperty apiModelProperty = field.getAnnotation(ApiModelProperty.class);
            String column = apiModelProperty != null ? apiModelProperty.value() : field.getName();

            // compare field values
            if (oldValue != null && newValue != null) {
                if (!oldValue.equals(newValue)) {
                    differentColumns.add(column);
                }
            } else if (oldValue == null && newValue != null) {
                differentColumns.add(column);
            } else if (oldValue != null && newValue == null) {
                differentColumns.add(column);
            }
        }

        return differentColumns;
    }
}

使用示例:

public class User {
    @ApiModelProperty(value = "User ID")
    private Long id;
    @ApiModelProperty(value = "User name")
    private String name;
    @ApiModelProperty(value = "User age")
    private Integer age;

    // getters and setters
}

public class Main {
    public static void main(String[] args) throws Exception {
        User oldUser = new User();
        oldUser.setId(1L);
        oldUser.setName("John");
        oldUser.setAge(20);

        User newUser = new User();
        newUser.setId(1L);
        newUser.setName("Jane");
        newUser.setAge(20);

        List<String> differentColumns = ObjectComparator.compareObjects(oldUser, newUser);

        System.out.println(differentColumns);
    }
}

输出结果:

[User name]

在这个例子中,我们比较了两个User对象的属性值,发现name属性的值不同,因此返回了列名"User name"。其中,列名是根据@ApiModelPropery注解的value值得到的,如果没有这个注解,则使用属性名作为列名

比较两个对象每个字段属性值不同的工具类返回所有属性值不同的列名有ApiModelProperty注解的话返回其value值

原文地址: https://www.cveoy.top/t/topic/ff4N 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录