我有一个可重复的注解
@Repeatable(Examples.class)
public @interface Example {
int value();
}
带有容器注解
@Retention(RetentionPolicy.RUNTIME)
public @interface Examples {
Example[] value();
}
然后我尝试启动这段代码
@Example(1)
@Example(2)
public class Test {
public static void main(String[] args) {
Example example = Test.class.getAnnotation(Example.class);
System.err.println(example);
}
}
但是它打印出 null
。怎么可能?
最佳答案
您应该仔细阅读有关 repeatable annotations 的文档.发生这种情况是因为不止一个可重复的注解被包装到容器注解中:
There are several methods available in the Reflection API that can be used to retrieve annotations. The behavior of the methods that return a single annotation, such as
AnnotatedElement.getAnnotationByType(Class<T>)
, are unchanged in that they only return a single annotation if one annotation of the requested type is present. If more than one annotation of the requested type is present, you can obtain them by first getting their container annotation.
所以你有几个选择
- 使用
getAnnotationsByType
方法
Example[] annotations = Test.class.getAnnotationsByType(Example.class);
- 使用
getAnnotation
使用容器注解
Example[] annotations = Test.class.getAnnotation(Examples.class).value();
关于java - getAnnotation 为多个注释返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39480561/