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.
解决方案
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());
};
}
}