java—在运行时是否可以访问类型参数上的注解?

0sgqnhkj  于 2021-06-27  发布在  Java
关注(0)|答案(2)|浏览(296)

java 8允许:

public List<@NonNull String> names;

但是有没有一种方法可以在运行时访问这个注解,或者它只对编译器插件可用?
有新的 Method#getAnnotatedReturnType 它提供了对返回类型的注解的访问,所以我希望 ParameterizedType 会有类似的 getActualAnnotatedTypeArguments 对于泛型类型参数也是这样,但它不存在。。。

5n0oy7gb

5n0oy7gb1#

新的api延续了传统,需要大量的 instanceof s和类型转换:

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;
    }
}

另请参见此答案的结尾,以获取处理其他场景(如类型变量、通配符类型和数组)的示例。

dpiehjr4

dpiehjr42#

确实有一种方法 getAnnotatedActualTypeArguments 但是在 AnnotatedParameterizedType ,不在 ParameterizedType 我在哪里找的。

相关问题