【问题标题】:Is it possible to access Java 8 type information at runtime?是否可以在运行时访问 Java 8 类型信息?
【发布时间】:2014-03-13 09:46:33
【问题描述】:

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

private List<@Email String> emailAddresses;

是否可以使用反射读取运行时使用的 String 类型的 @Email 注释?如果是这样,如何做到这一点?

更新:这是注解类型的定义:

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

【问题讨论】:

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

标签: java reflection annotations type-annotation


【解决方案1】:

是的,这是可能的。代表这种结构的反射类型称为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()

【讨论】:

  • 谢谢!我错过了对AnnotatedParameterizedType 的向下转换,因此没有看到getAnnotatedActualTypeArguments()
猜你喜欢
  • 1970-01-01
  • 2014-01-19
  • 1970-01-01
  • 1970-01-01
  • 2012-03-17
  • 1970-01-01
  • 2019-08-03
相关资源
最近更新 更多