两对象同字段差异比较

工具类

import com.sun.istack.internal.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.format.annotation.DateTimeFormat;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;


@Slf4j
public class ChangeRecordUtils {



    /**
     * 默认值
     */
    private static final String DEFAULT_VALUE = "";
    /**
     * 默认日期格式
     */
    private static final String DEFAULT_PATTERN = "yyyy-MM-dd";

    /**
     * 分隔符
     */
    private static final String SEPARATOR = ",";


    public static <T> String[] getRecordInfo(@NotNull T before, @NotNull T after) {
        return getRecordInfoByGroup(before, after, null);
    }

    /**
     * 是否相等
     *
     * @param before
     * @param after
     * @param group
     * @param <T>
     * @return
     */
    public static <T> boolean aequalsB(@NotNull T before, @NotNull T after, @NotNull String group) {
        String[] recordInfoByGroup = getRecordInfoByGroup(before, after, group);
        if (com.jcxx.saas.common.utils.StringUtils.isBlank(recordInfoByGroup[0]) &&
                com.jcxx.saas.common.utils.StringUtils.isBlank(recordInfoByGroup[1])) {
            return true;
        }
        return false;
    }

    /**
     * 获取不同值对比
     *
     * @param before
     * @param after
     * @param <T>
     * @return
     */
    public static <T> String[] getRecordInfoByGroup(@NotNull T before, @NotNull T after, @NotNull String group) {
        List<String> oldDataRecord = new LinkedList<>();
        List<String> newDataRecord = new LinkedList<>();
        //旧数据
        String oldData = "";
        //新数据
        String newData = "";
        String[] result = {oldData, newData};

        //获取修改前对象属性
        List<Field> oldObjfields = getObjAndSuperObjFilds(before, group);
        if (oldObjfields.size() < 1) {
            return result;
        }

        String fieldAnnotatioValue;
        //修改前值
        String beforeValue;
        //修改后值
        String afterValue;
        for (Field oldField : oldObjfields) {
            String oldFieldName = oldField.getName();
            //编辑前值
            beforeValue = getValueByFieldName(before, oldFieldName);
            //编辑后值
            afterValue = getValueByFieldName(after, oldFieldName);
            //判断前后值是否相等
            if (!Objects.equals(afterValue, beforeValue)) {
                fieldAnnotatioValue = getFieldAnnotatioValue(oldField);
                fieldAnnotatioValue = fieldAnnotatioValue == null ? "" : fieldAnnotatioValue;
                fieldAnnotatioValue = fieldAnnotatioValue.replaceAll(":", "");
                fieldAnnotatioValue = fieldAnnotatioValue.replaceAll(":", "");
                fieldAnnotatioValue = fieldAnnotatioValue + ":";
                oldDataRecord.add(fieldAnnotatioValue + beforeValue);
                newDataRecord.add(fieldAnnotatioValue + afterValue);
            }
        }
        oldData = Arrays.toString(oldDataRecord.toArray()).replace("]", "").replace("[", "");
        newData = Arrays.toString(newDataRecord.toArray()).replace("]", "").replace("[", "");
        //处理
        result[0] = oldData;
        result[1] = newData;
        return result;
    }


    /**
     * 获取对象某属性值
     *
     * @param obj
     * @param filedName
     * @param <T>
     * @return
     */
    private static <T> String getValueByFieldName(T obj, String filedName) {
        Class<?> objClass = obj.getClass();
        Class<?> objSuperclass = objClass.getSuperclass();
        Field field = getField(objClass, filedName);
        //父级属性
        field = (field == null) ? getField(objSuperclass, filedName) : field;
        //值
        return (field == null) ? DEFAULT_VALUE : getValueByField(field, obj);
    }


    /**
     * 获取对象所有属性
     *
     * @param obj
     * @param <T>
     * @return
     */
    private static <T> List<Field> getObjAndSuperObjFilds(T obj, String group) {
        //当前对象属性
        List<Field> objfields = new LinkedList<>();
        Class<?> objClass = obj.getClass();
        List<Field> fields1 = getFildListByClass(objClass, group);
        objfields.addAll(fields1);
        //父级对象属性
        Class<?> objSuperclass = objClass.getSuperclass();
        List<Field> fields2 = getFildListByClass(objSuperclass, group);
        objfields.addAll(fields2);
        return objfields;
    }


    /**
     * 获取filed
     *
     * @param objClass
     * @return
     */
    private static List<Field> getFildListByClass(Class<?> objClass, String group) {
        List<Field> objfields = new LinkedList<>();
        Field[] fields = objClass.getDeclaredFields();
        if (fields.length > 0) {
            for (Field field : fields) {
                Field targetField = getField(field);
                if (Objects.isNull(targetField)) {
                    continue;
                }
                if (targetField.isAnnotationPresent(SysContrast.class)) {
                    if (StringUtils.isNotBlank(group)) {
                        SysContrast annotation = targetField.getAnnotation(SysContrast.class);
                        String annotationGroup = annotation.group();
                        if (StringUtils.isNotBlank(annotationGroup)) {
                            String[] split = annotationGroup.split(",");
                            if (Arrays.asList(split).contains(group)) {
                                objfields.add(field);
                            }
                        }

                    } else {
                        objfields.add(field);
                    }

                } else {
                    objfields.add(field);
                }
            }
        }
        return objfields;
    }


    /**
     * 获取对象属性
     *
     * @param clazz
     * @param propertyName
     * @return
     */
    private static Field getField(Class<?> clazz, String propertyName) {
        if (clazz == null) {
            return null;
        }
        try {
            return clazz.getDeclaredField(propertyName);
        } catch (NoSuchFieldException e) {
            return getField(clazz.getSuperclass(), propertyName);
        }
    }


    /**
     * 根据属性获取值
     *
     * @param field
     * @param obj
     * @param <T>
     * @return
     */
    private static <T> String getValueByField(Field field, T obj) {
        field.setAccessible(true);
        Object value = null;
        try {
            value = field.get(obj);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            log.error("反射获取前信息失败{{}}", e.getMessage());
        }
        //获取属性值
        boolean annotationPresent = field.isAnnotationPresent(SysContrast.class);
        if (annotationPresent) {
            //获取名
            SysContrast annotation = field.getAnnotation(SysContrast.class);
            String readConverterExp = annotation.readConverterExp();
            //获取值
            //1.时间类型
            if (Date.class.isAssignableFrom(field.getType()) && value != null) {
                String pattern = annotation.dateFormat();
                if (StringUtils.isBlank(pattern)) {
                    pattern = DEFAULT_PATTERN;
                }
                SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                value = sdf.format(value);
            } else if (StringUtils.isNotBlank(readConverterExp)) {
                //2.需要转意
                value = convertByExp(ConvertUtils.toStr(value), annotation.readConverterExp(), annotation.separator());
            }
        } else {
            if (Date.class.isAssignableFrom(field.getType()) && value != null) {
                if (field.isAnnotationPresent(DateTimeFormat.class)) {
                    DateTimeFormat annotation = field.getAnnotation(DateTimeFormat.class);
                    String pattern = annotation.pattern();
                    if (StringUtils.isNotBlank(pattern)) {
                        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                        value = sdf.format(value);
                    }
                }
            }

        }
        return (value == null) ? DEFAULT_VALUE : ConvertUtils.toStr(value);
    }


    /**
     * 获取值
     *
     * @param field
     * @return
     */
    private static String getFieldAnnotatioValue(Field field) {
        SysContrast annotation = field.getAnnotation(SysContrast.class);
        return annotation.value();
    }


    /**
     * 获取属性
     *
     * @param field
     * @return
     */
    private static Field getField(Field field) {
        if (field == null) {
            return null;
        }
        boolean annotationPresent = field.isAnnotationPresent(SysContrast.class);
        if (annotationPresent) {
            return field;
        }
        return null;
    }


    /**
     * 解析导出值 0=男,1=女,2=未知
     *
     * @param propertyValue 参数值
     * @param converterExp  翻译注解
     * @param separator     分隔符
     * @return 解析后值
     */
    private static String convertByExp(String propertyValue, String converterExp, String separator) {
        StringBuilder propertyString = new StringBuilder();
        String[] convertSource = converterExp.split(",");
        for (String item : convertSource) {
            String[] itemArray = item.split("=");
            if (StringUtils.containsAny(separator, propertyValue)) {
                for (String value : propertyValue.split(separator)) {
                    if (itemArray[0].equals(value)) {
                        propertyString.append(itemArray[1] + separator);
                        break;
                    }
                }
            } else {
                if (itemArray[0].equals(propertyValue)) {
                    return itemArray[1];
                }
            }
        }
        return StringUtils.stripEnd(propertyString.toString(), separator);
    }
}

注解

import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;

@java.lang.annotation.Target(ElementType.FIELD)
@java.lang.annotation.Retention(RetentionPolicy.RUNTIME)
public @interface SysContrast {
    /**
     * 中文名
     */
    String value() default "";

    /**
     * 日期格式
     */
    String dateFormat() default "";

    /**
     * 读取内容转表达式 (如: 0=男,1=女,2=未知)
     */
    String readConverterExp() default "";


    /**
     * 另一个类中的属性名称,支持多级获取,以小数点隔开
     */
    String targetAttr() default "";


    /**
     * 分组分类
     */
    String group() default "";

    /**
     * 分隔符
     *
     * @return
     */
    String separator() default ",";
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值