我有类(class)人:
@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
。我不太明白我做错了什么。
最佳答案
您必须访问如下所示的注释。稍微修改了代码:
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());
};
}
}
关于java - 如何在java反射中获取注解值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28673228/