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"}]

 

 

 

 

 

 

 

 

 

 

上一篇:ORM框架入门实例3


下一篇:如何用SecureCRT 登录eNSP模拟器里的设备