使用Java反射机制实现对比两个对象的属性差异

2020-12-31  本文已影响0人  沁园Yann
1、对比两个对象的属性差异
/**
     * 获取两个对象之间的变化(仅对比当前对象写的属性,不会对比父类写的属性)
     * @param oldBean
     * @param newBean
     * @return
     */
    public String getObjectDifferent(Object oldBean, Object newBean) {
        if (oldBean != null && newBean!= null) {
            String modifyValue = "";
            try {
                Class clazz = oldBean.getClass();
                List<Field> fields = new ArrayList<>();
                fields.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
                //如果父类属性变化也记录
                fields.addAll(new ArrayList<>(Arrays.asList(clazz.getSuperclass().getDeclaredFields())));
                for (Field field : fields) {
                    if ("serialVersionUID".equals(field.getName())) {
                        continue;
                    }
                    PropertyDescriptor pd = new PropertyDescriptor(field.getName(), oldBean.getClass());
                    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())) {
                        modifyValue += field.getName() + ":" + o1 + "->" + o2 + "; ";
                    }
                }
                return modifyValue;
            } catch (Exception e) {
                e.printStackTrace();
                return e.toString();
            }
        } else {
            log.info("传入对象为空,保存 “修改操作” 系统敏感操作记录失败");
            return "保存 “修改操作” 传入对象为空";
        }
    }
2、获取对象不为空的属性
/**
     * 获取对象不为空的属性
     * @param object
     * @return
     */
    public String getObjectNotNull(Object object) {
        String str = "";
        if (object != null) {
            try {
                Field[] fields = object.getClass().getDeclaredFields();
                for (Field field : fields) {
                    if ("serialVersionUID".equals(field.getName())) {
                        continue;
                    }
                    PropertyDescriptor pd = new PropertyDescriptor(field.getName(), object.getClass());
                    Method getMethod = pd.getReadMethod();
                    Object obj = getMethod.invoke(object);
                    if (obj != null && (!StringUtil.isEmpty(obj.toString()))) {
                        str += field.getName() + ":" + obj + ";";
                    }
                }
            } catch (Exception ex) {
                return ex.toString();
            }

        }
        return str;
    }
上一篇下一篇

猜你喜欢

热点阅读