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]).通过上面的例子,你可以转换actualType为java.lang.Class.在其他情况下,它可能会有所不同(请参阅meriton的评论)