是否有可能在运行时访问Java 8类信息? [英] Is it possible to access Java 8 type informations at runtime?
问题描述
假设我有一类下面的成员,这使得使用Java 8型注释:
私人列表< @Email串>电子邮件地址;
是否可以读取使用反射在运行时String类型的使用给出的 @Email
标注?如果是这样,怎么会这样做?
更新:这是注释类型的定义:
@Target(值= ElementType.TYPE_USE)
@Retention(RetentionPolicy.RUNTIME)
公共@interface电子邮件{}
是的,它是可能的。反射式重presenting这种结构被称为<一href=\"http://docs.oracle.com/javase/8/docs/api/java/lang/reflect/AnnotatedParameterizedType.html\"><$c$c>AnnotatedParameterizedType$c$c>.这里是如何让你的注释的例子:
//获取电子邮件字段
现场emailAddressField = MyClass.class.getDeclaredField(emailAddresses);//字段的类型是两个参数和注释,
//将它转换为正确的类型再presentation
AnnotatedParameterizedType annotatedParameterizedType =
(AnnotatedParameterizedType)emailAddressField.getAnnotatedType();//获取所有类型参数
AnnotatedType [] = annotatedActualTypeArguments
annotatedParameterizedType.getAnnotatedActualTypeArguments();//其中包含注解的字符串参数
AnnotatedType stringParameterType = annotatedActualTypeArguments [0];//实际的注解
注释emailAnnotation = stringParameterType.getAnnotations()[0];的System.out.println(emailAnnotation); // @Email()
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 {}
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()
这篇关于是否有可能在运行时访问Java 8类信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!