如何獲得註釋值,我有類人:在Java反射
@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
。我不太明白我做錯了什麼。
當你有'Annotation a'使用它時,不要再查找它。如果你在調試器中看看這段代碼,它應該更清晰。 – 2015-02-23 11:56:41
@PeterLawrey它現在打印「@MaxLength(length = 3)」,但我只想要「3」,我找不到具體的批註工作方式。 – user2950602 2015-02-23 12:16:36