java两个对象数据差异比对

 public static Boolean compareObjects(Object oldObj, Object newObj)  {
        if (MD5Utils.encodeHexString(JsonUtil.toJson(oldObj).getBytes(StandardCharsets.UTF_8))
                .equals(MD5Utils.encodeHexString(JsonUtil.toJson(newObj).getBytes(StandardCharsets.UTF_8)))) {
            return Boolean.FALSE;
        }
        Field[] fields = oldObj.getClass().getDeclaredFields();
        Class<?> clazz2 = newObj.getClass();
        Boolean resultFlag = Boolean.FALSE;
        try {
            int i = 1;
            for (Field field : fields) {
                ReflectionUtils.makeAccessible(field);
                Field secondField = clazz2.getDeclaredField(field.getName());
                ReflectionUtils.makeAccessible(secondField);
                Object oldVal = field.get(oldObj);
                Object newVal = secondField.get(newObj);
                if (!Objects.equals(oldVal, newVal)) {
                    // todo 差异
                }
            }
        } catch (Exception e) {
            log.error("字段比对异常", e);
        }
        return resultFlag;
    }

你可能感兴趣的:(开发问题记录,spring,boot,spring,java,maven)