假设在使用Java 8类型注释的类中有以下成员:
private List<@Email String> emailAddresses;
是否有可能在运行时使用反射读取字符串类型上给出的@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()