如何从Java 8中的getAnnotatedParameterTypes()获取泛型类型信息?

Tav*_*nes 8 java generics reflection java-8 type-annotation

它似乎getAnnotatedParameterTypes()返回一个包含AnnotatedType原始类型而不是泛型类型的s 数组.例如:

public <T> void genericMethod(T t) {
}

@Test
public void testAnnotatedTypes() throws ReflectiveOperationException {
    Method method = getClass().getMethod("genericMethod", Object.class);

    Type type = method.getGenericParameterTypes()[0];
    assertTrue(type instanceof TypeVariable);

    AnnotatedType annotatedType = method.getAnnotatedParameterTypes()[0];

    // This fails; annotatedType implements only AnnotatedType
    assertTrue(annotatedType instanceof AnnotatedTypeVariable);

    // This fails too; type is a TypeVariable while annotatedType.getType() is
    // Object.class
    assertEquals(type, annotatedType.getType());
}
Run Code Online (Sandbox Code Playgroud)

分歧的原因是什么getGenericParameterTypes()

Sot*_*lis 7

有一个关于此错误报告,并且已经修复.

Method#getGenericParameterTypes()和之间有区别Method#getAnnotatedParameterTypes().

前者保证它返回的类型

如果形式参数类型是参数化类型,则为其返回的Type对象必须准确反映源代码中使用的实际类型参数.

如果形式参数类型是类型变量或参数化类型,则创建它.否则,它就解决了.

而后者则没有,至少不清楚:

返回一个AnnotatedType对象数组,表示使用类型来指定由此表示的方法/构造函数的形式参数类型Executable.

我们必须假设getAnnotatedParameterTypes()返回已擦除的类型(尽管它可能不是那样的).无界类型变量T被删除Object.如果你有<T extends Foo>,它将被删除Foo.

至于注释,关于从方法参数中的类型参数获取注释,没有办法给出上述内容.人们会认为它适用于田野.

public static void main(String[] args) throws Exception {
    Field field = Example.class.getField("field");
    AnnotatedParameterizedType annotatedParameterizedType = (AnnotatedParameterizedType) field
            .getAnnotatedType();

    System.out.println(annotatedParameterizedType
            .getAnnotatedActualTypeArguments()[0].getType());
    System.out.println(Arrays.toString(annotatedParameterizedType
            .getAnnotatedActualTypeArguments()[0].getAnnotations()));
}

@Retention(RetentionPolicy.RUNTIME)
@Target(value = { ElementType.TYPE_USE })
@interface Bar {
}

public List<@Bar String> field;
Run Code Online (Sandbox Code Playgroud)

打印

class java.lang.String
[@com.example.Example$Bar()]
Run Code Online (Sandbox Code Playgroud)

我非常认为这是一个需要修复的错误,并将遵循上面链接的错误报告.