8

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

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

不同意的原因是什么getGenericParameterTypes()

4

1 回答 1

7

有一个关于这个的错误报告,它已经被修复了。

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

前者保证它返回的类型

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

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

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

返回一个对象数组,AnnotatedType这些对象表示使用类型来指定 this 表示的方法/构造函数的形式参数类型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;

哪个打印

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

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

于 2014-04-14T17:51:12.930 回答