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

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


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();
}