是否可以在运行时访问 Java 8 类型信息? [英] Is it possible to access Java 8 type information at runtime?
本文介绍了是否可以在运行时访问 Java 8 类型信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我在使用 Java 8 类型注释的类中有以下成员:
Assuming I have the following member in a class which makes use of Java 8 type annotations:
private List<@Email String> emailAddresses;
是否可以使用反射读取在运行时使用的 String 类型给出的 @Email
注释?如果是这样,这将如何完成?
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 {}
推荐答案
是的,这是可能的.表示这种结构的反射类型称为AnnotatedParameterizedType代码>
.以下是如何获取注释的示例:
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屋!
查看全文