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

时间:2015-02-23 11:54:25

标签: java reflection annotations

我有班级人员:

@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。我不太明白我做错了什么。

2 个答案:

答案 0 :(得分:1)

您必须访问注释,如下所示。修改了一下代码:

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

答案 1 :(得分:0)

使用注释类名称,如 -

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

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

Annotation annotations[] = method.getAnnotations();

并迭代注释