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

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

问题描述

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天全站免登陆