在运行时是否可以访问类型参数上的注释? [英] Are annotations on a type parameter accessible in runtime?

查看:51
本文介绍了在运行时是否可以访问类型参数上的注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 8允许执行以下操作:

Java 8 allows things like:

public List<@NonNull String> names;

但是有没有一种方法可以在运行时访问此注释,或者仅对编译器插件可用?

But is there a way to access this annotation in runtime or is it available only to compiler plugins?

有一个新的Method#getAnnotatedReturnType可以访问返回类型上的注释,因此我希望ParameterizedType现在具有类似getActualAnnotatedTypeArguments的东西,它们对于泛型类型参数也可以做到这一点,但是它不存在. ..

There's new Method#getAnnotatedReturnType that provides access to annotations on the return type, so I was hoping ParameterizedType would now have something like getActualAnnotatedTypeArguments that would do the same for generic type arguments, but it doesn't exist...

推荐答案

新API继承了要求大量instanceof和类型强制转换的传统:

The new API continues the tradition of requiring lots of instanceofs and type casts:

import java.lang.annotation.*;
import java.lang.reflect.*;
import java.util.*;
import java.util.stream.*;

public class AnnoTest {
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE_USE)
    @interface NonNull {}

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE_USE)
    @interface NonEmpty {}

    List<@NonNull String> list;
    Map<@NonNull Integer, @NonNull @NonEmpty Set<String>> map;
    Object plain;

    public static void main(String[] args) throws ReflectiveOperationException {
        for(Field field: AnnoTest.class.getDeclaredFields()) {
            AnnotatedType at = field.getAnnotatedType();
            System.out.println(formatType(at)+" "+field.getName());
        }
    }
    static CharSequence formatType(AnnotatedType type) {
        StringBuilder sb=new StringBuilder();
        for(Annotation a: type.getAnnotations()) sb.append(a).append(' ');
        if(type instanceof AnnotatedParameterizedType) {
            AnnotatedParameterizedType apt=(AnnotatedParameterizedType)type;
            sb.append(((ParameterizedType)type.getType()).getRawType().getTypeName());
            sb.append(Stream.of(apt.getAnnotatedActualTypeArguments())
                .map(AnnoTest::formatType).collect(Collectors.joining(",", "<", ">")));
        }
        else sb.append(type.getType().getTypeName());
        return sb;
    }
}

另请参阅此答案的末尾,以获取处理其他情况(例如类型变量,通配符类型和数组)的示例

See also the end of this answer for an example handling the other scenarios like type variables, wild card types and arrays.

这篇关于在运行时是否可以访问类型参数上的注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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