java - 如何在java反射中获取注解值

标签 java reflection annotations

我有类(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/

相关文章:

java - java中从json数组中获取值

java - 为什么本例中的字符串 helloWorld 没有改变?

java - 当在运行时收到谓词函数的名称时,如何将函数作为谓词传递给另一个函数?

c# - 编译器说缺少动态属性,但我可以看到它

c# - 如何通过 FieldInfo.GetValue() 获取 Nullable<T> (而不是基础值)?

java - 尽管链接和验证成功,为什么着色器程序无法编译?

java - 启用 Java 详细日志记录 (rt.jar)

java - 如何确定(在运行时)变量是否被注释为已弃用?

java - 重写方法中的方法参数注释

java - 像@depreciated这样的注释