Java 对象字段属性差异对比工具类 (修改前&修改后的属性值)

2021/6/10 12:21:10

本文主要是介绍Java 对象字段属性差异对比工具类 (修改前&修改后的属性值),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

工具类:    ContrastObjUtil

 

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * 属性差异 工具类
 */
public class ContrastObjUtil {

    public static String comparObj(Object oldBean, Object newBean) {
        JSONArray array = new JSONArray();
        try {
            Class clazz = oldBean.getClass();
            Field[] fields = oldBean.getClass().getDeclaredFields();
            int i = 1;

            for (Field field : fields) {
                if ("serialVersionUID".equals(field.getName())) {
                    continue;
                }
                PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
                Method getMethod = pd.getReadMethod();
                Object o1 = getMethod.invoke(oldBean);
                Object o2 = getMethod.invoke(newBean);
                if (o1 == null || o2 == null) {
                    continue;
                }
                if (!o1.toString().equals(o2.toString())) {
                    // 要显示的字段名
                    String fieldName = "";
                    fieldName = field.getName();

                    JSONObject json = new JSONObject();
                    json.put("type", fieldName);
                    json.put("oldValue", o1);
                    json.put("newValue", o2);
                    array.add(json);
                    i++;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return array.toJSONString();
    }
}

 

 

 

测试:

public void testCompare(){
        User u1 = new User();
        u1.setId(1);
        u1.setName("小明");
        u1.setPhone("12580");

        User u2 = new User();
        u2.setId(1);
        u2.setName("小明");
        u2.setPhone("12580999");

        String result = ContrastObjUtil.comparObj(u1, u2);
        System.out.println(result);//[{"newValue":"12580999","oldValue":"12580","type":"phone"}]
    }

 

 

结果:

[{"newValue":"12580999","oldValue":"12580","type":"phone"}]

 

 

 

 

 

 

 

 

 

 



这篇关于Java 对象字段属性差异对比工具类 (修改前&修改后的属性值)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程