How to get annotation values in java reflection

2019-09-08 07:58发布

问题:

I have class Person:

@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;
}


}

Then I'm trying to print annotation values of methods of Peson object.

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

I want it to print annotation values, but it prints null. I m not quite understand what am I doing wrong.

回答1:

You have to access the annotations as shown below. Have modified the code a bit:

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


回答2:

Use the annotation class name like -

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

or you can get all annotation array using another function -

Annotation annotations[] = method.getAnnotations();

and iterate the annotations