繁体   English   中英

如何在内部泛型类型上使用注释?

[英]How to get annotation used on inner generic type?

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

假设您有一个 class:

import java.util.List;

public class Sample
{

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

}

如您所见,字段类型是List<List<String>> 假设您有 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<String> 但是,因为它不是AnnotatedParameterizedType类型,所以我无法访问@Second注释。

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

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

您应该能够以与第一个注释相同的方式访问第二个注释。 annotatedActualTypeArgument转换为AnnotatedParameterizedType ,然后获取带注释的实际类型参数:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM