java - getAnnotation 为多个注释返回 null

标签 java

我有一个可重复的注解

@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.

所以你有几个选择

  1. 使用getAnnotationsByType方法
Example[] annotations = Test.class.getAnnotationsByType(Example.class);
  1. 使用getAnnotation使用容器注解
Example[] annotations = Test.class.getAnnotation(Examples.class).value();

关于java - getAnnotation 为多个注释返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39480561/

相关文章:

java - RESTful 服务客户端可以作为 SOAP 服务的服务器吗?

java - 如何在 Spring Controller 的每个方法之前使用 AOP 执行一些代码并拥有 Method 对象

java - c3p0配置shell命令

java - android中的默认微调器样式

java - Redis SCAN 返回无效游标

java - Eclipse RCP - 使用片段提供翻译

java - 如何避免 ConcurrentHashMap 使用

java - 使用 Java 8 模块的 Gradle Android 项目

java - HtmlUnit - getByXPath 元素类型未知

Java 程序因打印行而变慢