如何在 java 反射中获取注释值

How to get annotation values in java reflection

我有class个人:

@Retention(RetentionPolicy.RUNTIME)
@interface MaxLength {
int length();
}

@Retention(RetentionPolicy.RUNTIME)
@interface NotNull {

}

public class Person {

private int age;

private String name;

public Person(int age, String name) {
    this.age = age;
    this.name = name;
}

@NotNull
public int getAge() {
    return this.age;
}

@MaxLength(length = 3)
public String getName() {
    return this.name;
}


}

然后我尝试打印 Peson 对象方法的注释值。

 for (Method method : o.getClass().getDeclaredMethods()) {
        if (method.getName().startsWith("get")) {
            Annotation[] annotations = method.getDeclaredAnnotations();
            for (Annotation a : annotations) {
              Annotation annotation = method.getAnnotation(a.getClass());
                    System.out.println(method.getName().substring(3) + " " +
                           annotation);
            }
        }
    }

我想让它打印注释值,但它打印了 null。我不太明白我做错了什么。

您必须访问如下所示的注释。稍微修改了代码:

Person personobject = new Person(6, "Test");
MaxLength maxLengthAnnotation;
Method[] methods = personobject.getClass().getDeclaredMethods();
for (Method method : methods) {
if (method.getName().startsWith("get")) {
    // check added to avoid run time exception
    if(method.isAnnotationPresent(MaxLength.class)) {
        maxLengthAnnotation = method.getAnnotation(MaxLength.class);
        System.out.println(method.getName().substring(3) + " " + maxLengthAnnotation.length());
    };
  }
}

使用注释 class 名称,如 -

method.getAnnotation(MaxLength.class);
method.getAnnotation(NotNull.class);

或者您可以使用另一个函数获取所有注释数组 -

Annotation annotations[] = method.getAnnotations();

并迭代注释