java对比两个对象的值是否有差异(比较相同属性名的字段)

    /**
     * 对比两个对象的值是否有差异
     * @param source 对象1
     * @param target 对象2
     * @param isInclude 属性集合是发需要包含对象字段
     * @param fields 属性集合
     * @param 
     * @return
     */
    public static  Map compareBean(T source, T target, boolean isInclude, String... fields) {
        Map sourceMap = BeanUtil.beanToMap(source);
        Map targetMap = BeanUtil.beanToMap(target);
        Map resultMap = new HashMap<>(16);
        for (Map.Entry entry : sourceMap.entrySet()) {
            if (ArrayUtil.isNotEmpty(fields)) {
                if (isInclude && !ArrayUtil.contains(fields, entry.getKey())) {
                    continue;
                }
                if (!isInclude && ArrayUtil.contains(fields, entry.getKey())) {
                    continue;
                }
            }

            Object oldVal = entry.getValue();
            Object newVal = targetMap.get(entry.getKey());
            boolean isOldAndNewBlank = (oldVal == null || (oldVal instanceof String && StringUtils.isBlank((String) oldVal)))
                    && (newVal == null || (newVal instanceof String && StringUtils.isBlank((String) newVal)));
            if (isOldAndNewBlank) {
                continue;
            }
            if (!Objects.equals(oldVal, newVal)) {
                resultMap.put(entry.getKey(), String.format("oldVal:%s, newVal:%s", oldVal, newVal));
            }
        }
        return resultMap;
    }

你可能感兴趣的:(java,开发语言)