在Java反射
如何获得注释值,我有类人:在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
。我不太明白我做错了什么。
回答:
您必须访问注释,如下所示。已经修改了代码位:
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());
};
}
}
回答:
使用注释类名一样 -
method.getAnnotation(MaxLength.class); method.getAnnotation(NotNull.class);
或者您可以使用其他的功能得到所有注释阵列 -
Annotation annotations[] = method.getAnnotations();
和迭代的注解
以上是 在Java反射 的全部内容, 来源链接: utcz.com/qa/265046.html