lundi 23 février 2015

How to get annotation values in java reflection

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.






Aucun commentaire:

Enregistrer un commentaire