繁体   English   中英

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

[英]Is it possible to access Java 8 type information at runtime?

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

private List<@Email String> emailAddresses;

是否可以使用反射读取在运行时使用的String类型上给出的@Email注释? 如果是这样,怎么办呢?

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

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

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

暂无
暂无

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

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