这好像是 getAnnotatedParameterTypes() 返回一个数组 AnnotatedTypes 持有原始类型,而不是通用类型。例如:

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()?

有帮助吗?

解决方案

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

有一个区别 Method#getGenericParameterTypes()Method#getAnnotatedParameterTypes().

前者对其返回的类型做出保证

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

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

而后者则没有,至少不明确:

返回一个数组 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;

打印

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

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top