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

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

 public  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()); } 

getGenericParameterTypes()不一致的原因是什么?

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

Method#getGenericParameterTypes()Method#getAnnotatedParameterTypes()之间存在差异。

前者保证它返回的类型

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

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

虽然后者没有,至少不清楚:

返回AnnotatedType对象的数组,这些对象表示使用类型来指定此Executable表示的方法/构造函数的forms参数类型。

我们必须假设getAnnotatedParameterTypes()返回已擦除的类型(尽管它可能不是那种方式)。 无界类型变量T被擦除为Object 。 如果你有 ,它将被删除为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; 

打印

 class java.lang.String [@com.example.Example$Bar()] 

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