一叶飘零_sweeeet 2023-05-30 17:40 采纳率: 33.3%
浏览 20

java怎么通过反射给成员变量添加自定义注解

java怎么通过反射给成员变量添加自定义注解,请写出示例代码和测试用例,注意要用到反射哦.

  • 写回答

1条回答 默认 最新

  • 一起看海呦 2023-05-30 19:39
    关注
    
    public class Test {
        public String name;
        public int age;
    }
    
    public class Main {
        public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
            // 获取Test类
            Class<Test> clazz = Test.class;
            // 获取name字段
            Field nameField = clazz.getDeclaredField("name");
            // 将@MyAnnotation注解添加到name字段
            nameField.setAnnotation(MyAnnotation.class.getConstructor(String.class).newInstance("name annotation"));
    
            // 获取age字段
            Field ageField = clazz.getDeclaredField("age");
            // 将@MyAnnotation注解添加到age字段
            ageField.setAnnotation(MyAnnotation.class.getConstructor(String.class).newInstance("age annotation"));
    
            // 测试获取注解
            Test test = new Test();
            MyAnnotation nameAnnotation = nameField.getAnnotation(MyAnnotation.class);
            System.out.println(nameAnnotation.value()); // name annotation
            MyAnnotation ageAnnotation = ageField.getAnnotation(MyAnnotation.class);
            System.out.println(ageAnnotation.value()); // age annotation
        }
    }
    
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.FIELD)
    @interface MyAnnotation {
        String value();
    }
    
    评论

报告相同问题?

问题事件

  • 创建了问题 5月30日