【反射】操作日志,实体类内容变更记录

实体类比对工具类:

import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;

@Component
public class BeanChangeUtil {
    private static BMLoader staticBmLoader;

    @Autowired
    private BMLoader bmLoader;

    @PostConstruct
    private void initStaticBmLoader() {
        staticBmLoader = this.bmLoader;
    }

    public static <T> String contrastObj(Object oldBean, Object newBean) {
        // 创建字符串拼接对象
        StringBuilder str = new StringBuilder();
        // 转换为传入的泛型T
        T pojo1 = (T) oldBean;
        T pojo2 = (T) newBean;
        // 通过反射获取类的Class对象
        Class clazz = pojo1.getClass();
        // 获取类型及字段属性
        Field[] fields = clazz.getDeclaredFields();
        return jdk8Before(fields, pojo1, pojo2, str, clazz);
//        return jdk8OrAfter(fields, pojo1, pojo2, str,clazz);
    }

    // jdk8 普通循环方式
    public static <T> String jdk8Before(Field[] fields, T pojo1, T pojo2, StringBuilder str, Class clazz) {
        int i = 1;
        try {
            for (Field field : fields) {
                if (field.isAnnotationPresent(PropertyMsg.class)) {
                    PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
                    // 获取对应属性值
                    Method getMethod = pd.getReadMethod();
                    Object o1 = getMethod.invoke(pojo1);
                    Object o2 = getMethod.invoke(pojo2);
                    if (o1 == null || o2 == null) {
                        continue;
                    }
                    if (!o1.toString().equals(o2.toString())) {
                        if(field.isAnnotationPresent(TransCode.class)){
                            final String key = field.getAnnotation(TransCode.class).key();
                            o1 = staticBmLoader.getBmStrToZw((String) o1, key);
                            o2 = staticBmLoader.getBmStrToZw((String) o2, key);
                        }
                        str.append(field.getAnnotation(PropertyMsg.class).value() + ":" + "修改前=>" + o1 + ",修改后=>" + o2 + "\n");
                        i++;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str.toString();
    }

    // lambda表达式,表达式内部的变量都是final修饰,需要传入需要传入final类型的数组
    public String jdk8OrAfter(Field[] fields, T pojo1, T pojo2, StringBuilder str, Class clazz) {
        final int[] i = {1};
        Arrays.asList(fields).forEach(f -> {
            if (f.isAnnotationPresent(PropertyMsg.class)) {
                try {
                    PropertyDescriptor pd = new PropertyDescriptor(f.getName(), clazz);
                    // 获取对应属性值
                    Method getMethod = pd.getReadMethod();
                    Object o1 = getMethod.invoke(pojo1);
                    Object o2 = getMethod.invoke(pojo2);
                    if (o1 == null || o2 == null) {
                        return;
                    }
                    if (!o1.toString().equals(o2.toString())) {
                        str.append(f.getAnnotation(PropertyMsg.class).value() + ":" + "修改前=>" + o1 + "\t修改后=>" + o2 + "\n");
                        i[0]++;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        return str.toString();
    }
}

 调用类:

String optComment = BeanChangeUtil.contrastObj(oldTest1, test1);
optComment += BeanChangeUtil.contrastObj(oldTest2, test2);

实体类:

public class Test {
    private String regId;
    @PropertyMsg("报名类型")
    @TransCode(key="SchoolType")
    private String regType;

}

PropertyMsg.java

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface PropertyMsg {
    String value();
}

TransCode.java

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface TransCode {
    String key();
}

 

获取接口所有实现类:

private void loadCustomBm() {
   try {
           Reflections reflections = new Reflections("com.xxx.xxx.constant");
           Set<Class<? extends CustomBmHelper>> subTypesOf = reflections.getSubTypesOf(CustomBmHelper.class);
           for (Class<? extends CustomBmHelper> bmHelper : subTypesOf) {
               Method loadCustomBm = bmHelper.getDeclaredMethod("loadCustomBm");
               loadCustomBm.setAccessible(true);
               Map<String, Map<String, String>> invoke = (Map<String, Map<String, String>>) loadCustomBm.invoke(bmHelper.newInstance());
               BmMapWrapper bmMapWrapper = new BmMapWrapper();
               String key = invoke.keySet().iterator().next();
               Map<String, String> map = invoke.get(key);

               for(Map.Entry<String, String> entry : map.entrySet()){
                   bmMapWrapper.map.put(entry.getKey(), entry.getValue());
                   bmMapWrapper.bmOrderList.add(new BmMapWrapper.BmItem(entry.getKey(), entry.getValue()));
               }
               bmMap.put(key, bmMapWrapper);
           }
       } catch (Exception e) {
      e.printStackTrace();
   }
}

接口:

public interface CustomBmHelper {

    /**
     * 获取所有的代码数据。
     * @return 映射形式返回代码数据。
     */
    Map<String, Map<String, String>> loadCustomBm();
}

参数:

public static class CheckResult implements CustomBmHelper {
    public static final String WAIT = "0";
    public static final String PASS = "1";
    public static final String NO_PASS = "2";
    public static final String NO_DATA = "9";

    public static final Map<String, String> TRANS_MAP
        = MapHelper.ofHashMap(
        WAIT, "待审核",
        PASS, "审核通过",
        NO_PASS, "审核不通过",
        NO_DATA, "服务不通"
    );

    @Override
    public Map<String, Map<String, String>> loadCustomBm() {
        Map<String, Map<String, String>> map = new HashMap<>();
        map.put("CheckResult", TRANS_MAP);
        return map;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值