比较两个实体类的属性值工具

 

public static Map<String, CompareDTO> compareFields(Object source, Object target, List<String> comparedPropertyList) {
        try {
            Map<String, CompareDTO> map = Maps.newHashMap();

            if (CollectionUtils.isEmpty(comparedPropertyList)) {
                return null;
            }

            if (source == null || target == null) {
                throw new BizException("source or target is null");

            }

            // 只有两个对象都是同一类型的才有可比性
            if (source.getClass() != target.getClass()) {
                throw new BizException("incompatible type");
            }

            Class clazz = source.getClass();
            // 获取object的属性描述
            PropertyDescriptor[] pds = Introspector.getBeanInfo(clazz, Object.class).getPropertyDescriptors();
            // 这里就是所有的属性了
            for (PropertyDescriptor pd : pds) {
                // 属性名
                String name = pd.getName();
                // 如果不需要比较,跳到下一次循环
                if (!comparedPropertyList.contains(name)) {
                    continue;
                }

                // get方法
                Method readMethod = pd.getReadMethod();
                // 在obj1上调用get方法等同于获得obj1的属性值
                Object o1 = readMethod.invoke(source);
                // 在obj2上调用get方法等同于获得obj2的属性值
                Object o2 = readMethod.invoke(target);
                if (o1 == null && o2 == null) {
                    continue;
                } else if (o1 == null && o2 != null) {
                    CompareDTO compareDTO = new CompareDTO();
                    compareDTO.setOldValue(o1);
                    compareDTO.setNewValue(o2);
                    map.put(name, compareDTO);
                    continue;
                }
                // 比较这两个值是否相等,不等就可以放入map
                if (!o1.equals(o2)) {
                    CompareDTO compareDTO = new CompareDTO();
                    compareDTO.setOldValue(o1);
                    compareDTO.setNewValue(o2);
                    map.put(name, compareDTO);
                }
            }

            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值