反射的常用api及在工作当中的使用

反射的常用api方法

Method.invoke()//方法自己调用自己,方法调用必须通过object.method()方式,method对象本身是无法调用自己的。

Method.getParameterTypes()  //获得参数类型

Method.getReturnType() //获得返回值类型

Method.getParameterCount() //获得方法的参数个数

Method.getName() //获得方法名称

Method.getExceptionTypes() //获得方法抛出哪些异常

method.getAnnotation() //获得注解

参考https://www.cnblogs.com/bitbitbyte/p/12536575.html获取父类的方法

自己工作的实际运用

private <T> void contrastValue(T newer,T older,StringBuilder sb){
        Class<?> newClass = newer.getClass();
        // 保存属性对象数组到列表
        List<Field> newFieldsList = Lists.newArrayList();
        // 遍历所有父类字节码对象
        while (newClass!=null){
            // 获取字节码对象的属性对象数组
            Field[] declaredFields = newClass.getDeclaredFields();
            //将`Filed[]`数组转换为`List<>`然后再将其拼接至`ArrayList`上
            newFieldsList.addAll(Arrays.asList(declaredFields));
            // 获得父类的字节码对象
            newClass = newClass.getSuperclass();
        }
        List<Field> oldFieldsList = Lists.newArrayList();
        Class<?> oldClass = older.getClass();
        // 遍历所有父类字节码对象
        while (oldClass!=null){
            // 获取字节码对象的属性对象数组
            Field[] declaredFields = oldClass.getDeclaredFields();
            //将`Filed[]`数组转换为`List<>`然后再将其拼接至`ArrayList`上
            oldFieldsList.addAll(Arrays.asList(declaredFields));
            // 获得父类的字节码对象
            oldClass = oldClass.getSuperclass();
        }
        try {
            for (Field field : newFieldsList) {
                //反射时访问私有变量
                field.setAccessible(true);
                String newName = field.getName();
                if (field.get(newer)!=null){
                    ApiModelProperty annotation = field.getAnnotation(ApiModelProperty.class);
                    for (Field oldField : oldFieldsList) {
                        oldField.setAccessible(true);
                        String oldName = oldField.getName();
                        if (oldName.equals(newName)){
                            sb.append(annotation.value()+":"+field.get(newer) + " => " + oldField.get(older) + ";" );
                            System.out.println(sb);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值