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

时间秒杀一切 提交于 2019-12-18 12:54:43

问题


Assuming I have the following member in a class which makes use of Java 8 type annotations:

private List<@Email String> emailAddresses;

Is it possible to read the @Email annotation given on the String type use at runtime using reflection? If so, how would this be done?

Update: That's the definition of the annotation type:

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

回答1:


Yes it is possible. The reflection type representing this kind of structure is called AnnotatedParameterizedType. Here is an example of how to get your annotation:

// 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()


来源:https://stackoverflow.com/questions/22374612/is-it-possible-to-access-java-8-type-information-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!