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

标签 java generics reflection java-8 type-annotation

似乎 getAnnotatedParameterTypes() 返回一个包含原始类型而非通用类型的 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()不一致的原因是什么?

最佳答案

有一个 bug report about this ,此问题已得到修复。

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

前者保证它返回的类型

If a formal parameter type is a parameterized type, the Type object returned for it must accurately reflect the actual type parameters used in the source code.

If a formal parameter type is a type variable or a parameterized type, it is created. Otherwise, it is resolved.

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

Returns an array of AnnotatedType objects that represent the use of types to specify formal parameter types of the method/constructor represented by 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()]

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

关于java - 如何从 Java 8 中的 getAnnotatedParameterTypes() 获取泛型类型信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23025363/

相关文章:

java - 在另一个 xsd 中引用另一个 xsd 元素?

java - 具有不同具体类型作为方法参数的接口(interface)实现

java - 如何仅获取 java 类的 protected 和公共(public)构造函数?

c# - 如何通过反射过滤任何属性的集合?

java - 分解单个用户输入并将其存储在两个不同的变量中。 ( java )

java - 将日期格式从 Java 移植到 C++

Java XML 解析器添加不必要的 xmlns 和 xml :space attributes

delphi - 如何测试泛型接口(interface)的类型?

Java 泛型 : Type mismatch: cannot convert from Integer to K

css - 将颜色添加到 css -webkit-box-reflect 而不是图像