是否可以在运行时访问Java 8类型信息? [英] Is it possible to access Java 8 type information at runtime?

查看:118
本文介绍了是否可以在运行时访问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;

是否可以阅读 @Email String类型给出的注释在运行时使用反射?如果是这样,将如何做?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆