如何使用java反射获取类型参数值?

mik*_*1aj 11 java generics reflection

interface Foo<T> { ... }
class Bar implements Foo<Baz> { ... }
Run Code Online (Sandbox Code Playgroud)

我有一个Bar对象.如何获得它的价值T(Baz)?

到目前为止,我只是设法获得界面T,但我看不出有办法获得它的价值.

提前致谢.

Boz*_*zho 20

Type type = bar.getClass().getGenericInterfaces()[0];

if (type instanceof ParameterizedType) {
    Type actualType = ((ParameterizedType) type).getActualTypeArguments()[0];
    System.out.println(actualType);
}
Run Code Online (Sandbox Code Playgroud)

当然,在一般情况下,你应该迭代数组,而不是假设它有一个元素([0]).通过上面的例子,你可以转换actualTypejava.lang.Class.在其他情况下,它可能会有所不同(请参阅meriton的评论)

  • 请注意,通常,`actualType`不一定是普通的`java.lang.Class` - 它也可以是`GenericArrayType`,`ParametrizedType`或`TypeVariable`. (3认同)