是否可能在运行时访问Java 8的类型信息?

16
假设我在一个使用Java 8类型注释的类中有以下成员:

假设我在一个使用Java 8类型注释的类中有以下成员:

private List<@Email String> emailAddresses;

在运行时使用反射读取 String 类型上标注的 @Email 注解是否可能?如果可以,该如何实现?

更新:以下是该注解类型的定义:

@Target(value=ElementType.TYPE_USE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Email {}

你尝试过定义这样的注解并使用它吗?我没有,但我怀疑这不适用于泛型,因为它们在运行时被擦除... 从逻辑上讲,你的注解也会被擦除。 - fge
我已经声明了注解并使用它(更新问题以包括注解定义)。我可以访问列表的元素类型String(实际上没有被擦除)。我不知道的是如何访问注解。 - Gunnar
@Gunnar 考虑到类型擦除,为什么 String 列表类型没有被擦除? - timekeeper
@AayushKumarSingha 类型擦除不适用于字段或方法定义中使用的声明类型。例如,有关更多信息,请参见此问题 - Gunnar
1个回答

16

可以做到。代表这种结构的反射类型称为 AnnotatedParameterizedType。以下是获取注释的示例:

// get the email field 
Field emailAddressField = MyClass.class.getDeclaredField("emailAddresses");

// the field's type is both parameterized and annotated,
// cast it to the right type representation
AnnotatedParameterizedType annotatedParameterizedType =
        (AnnotatedParameterizedType) emailAddressField.getAnnotatedType();

// get all type parameters
AnnotatedType[] annotatedActualTypeArguments = 
        annotatedParameterizedType.getAnnotatedActualTypeArguments();

// the String parameter which contains the annotation
AnnotatedType stringParameterType = annotatedActualTypeArguments[0];

// The actual annotation
Annotation emailAnnotation = stringParameterType.getAnnotations()[0]; 

System.out.println(emailAnnotation);  // @Email()

3
谢谢!我之前漏掉了将类型向下转换为“AnnotatedParameterizedType”,因此没有注意到“getAnnotatedActualTypeArguments()”。 - Gunnar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接