自学内容网 自学内容网

java反射高级用列(脱敏+aop)

ClassUtils 、FieldUtils、MethodUtils、ReflectionUtils高级

List<String> list = new ArrayList<>();
Class<?> userClass = ClassUtils.getUserClass(list.getClass());
System.out.println(Collection.class.isAssignableFrom(userClass));
Class<?> clazz = Class.forName("com.sd.entity.User");
Object instance = clazz.getDeclaredConstructor().newInstance();
BeanUtils.populate(clazz, map);
instanceof

ReflectionUtils.doWithFields(MyClass.class, field -> {
   
    // 对每个字段执行操作
});

ReflectionUtils.doWithMethods(MyClass.class, method -> {
   
    // 对每个方法执行操作
});

ReflectionUtils.doWithFields(MyClass.class, field -> {
   
    // 对每个带有特定注解的字段执行操作
}, field -> field.isAnnotationPresent(MyAnnotation.class));

ReflectionUtils.doWithMethods(MyClass.class, method -> {
   
    // 对每个带有特定注解的方法执行操作
}, method -> method.isAnnotationPresent(MyAnnotation.class));

   //获取类的所有带有特定注解的字段
List<Field> fields = FieldUtils.getFieldsListWithAnnotation(MyClass.class, MyAnnotation.class);

    //获取字段值
Field field = ReflectionUtils.findField(MyClass.class, "myField");
Object fieldValue = ReflectionUtils.getField(field, myClassInstance);
    //读取字段值(忽略访问修饰符)
Object fieldValue = FieldUtils.readField(field, myClassInstance, true);//readStaticField读取静态值

   //设置字段值
Field field = ReflectionUtils.findField(MyClass.class, "myField");//字段名称
ReflectionUtils.setField(field, myClassInstance, "newValue");
FieldUtils.writeField(field, myClassInstance, "newValue", true);

实列

作用域方法上
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SensitiveData {
   
}
作用域字段
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SensitiveInfo {
   
    Type value() default Type.DEFAULT;

    

原文地址:https://blog.csdn.net/qq_37792401/article/details/136273903

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!