【问题标题】:How to get annotation used on inner generic type?如何在内部泛型类型上使用注释?
【发布时间】:2023-03-11 00:50:02
【问题描述】:

我的问题有点高级的反射问题。

假设你有一个班级:

import java.util.List;

public class Sample
{

    private List<@First List<@Second String>> field;

}

如您所见,字段类型为List&lt;List&lt;String&gt;&gt;。假设您有 2 个不同的注释:@First@Second。这些注释分别放在该字段的泛型类型上。现在,我的目标是在运行时访问这两个注解。

这是我的代码:

Field field = Sample.class.getDeclaredField("field");
AnnotatedType annotatedType = field.getAnnotatedType();
AnnotatedParameterizedType annotatedParameterizedType = (AnnotatedParameterizedType) annotatedType;

当我在字段上调用getAnnotatedType() 时,它会返回一个AnnotatedParameterizedType

AnnotatedType annotatedActualTypeArgument = annotatedParameterizedType.getAnnotatedActualTypeArguments()[0];
Annotation firstAnnotation = annotatedActualTypeArgument.getAnnotations()[0];

getAnnotatedActualTypeArguments() 方法实际上给了我@First 注释。

ParameterizedType innerType = (ParameterizedType) annotatedActualTypeArgument.getType();

但是,当我尝试获取内部泛型参数的类型时,它给了我一个ParameterizedType。正确定义了最内层参数的类型:List&lt;String&gt;。但是,因为它不是AnnotatedParameterizedType 类型,所以我无法访问@Second 注释。

有什么方法可以在运行时访问第二个注释吗?

【问题讨论】:

    标签: java generics reflection annotations


    【解决方案1】:

    首先注释类型Second必须声明为@Retention设置为RetentionPolicy.RUNTIME,以便它们保留在类文件中并且可以通过JVM使用反射来读取。

    您应该能够像访问第一个注释一样访问第二个注释。将annotatedActualTypeArgument转换为AnnotatedParameterizedType,然后得到带注释的实际类型参数:

    AnnotatedParameterizedType innerAnnotatedParameterizedType = (AnnotatedParameterizedType) annotatedActualTypeArgument;
    AnnotatedType innerAnnotatedActualTypeArgument = innerAnnotatedParameterizedType.getAnnotatedActualTypeArguments()[0];
    Annotation secondAnnotation = innerAnnotatedActualTypeArgument.getAnnotations()[0];
    

    【讨论】:

      猜你喜欢
      • 2020-09-02
      • 2021-07-14
      • 1970-01-01
      • 2023-03-18
      • 2021-05-13
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 2011-01-01
      相关资源
      最近更新 更多