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

前端 未结 1 1698
抹茶落季
抹茶落季 2020-12-31 05:58

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

private List<@Email String> emailAddresses;
相关标签:
1条回答
  • 2020-12-31 07:02

    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()
    
    0 讨论(0)
提交回复
热议问题