【发布时间】:2023-03-11 00:50:02
【问题描述】:
我的问题有点高级的反射问题。
假设你有一个班级:
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 注释。
有什么方法可以在运行时访问第二个注释吗?
【问题讨论】:
标签: java generics reflection annotations