如何在java反射中获取注释值 [英] How to get annotation values in java reflection

查看:32
本文介绍了如何在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 对象方法的注释值.

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);
            }
        }
    }

我希望它打印注释值,但它打印 null.我不太明白我做错了什么.

I want it to print annotation values, but it prints null. I m not quite understand what am I doing wrong.

推荐答案

您必须访问如下所示的注释.稍微修改了一下代码:

You have to access the annotations as shown below. Have modified the code a bit:

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反射中获取注释值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆