interface Foo<T> { ... }
class Bar implements Foo<Baz> { ... }
我有一个Bar
对象。如何获得它的价值T
(Baz
)?
到目前为止,我只设法获得了和的接口T
,但是我看不到获得其价值的方法。
提前致谢。
Type type = bar.getClass().getGenericInterfaces()[0];
if (type instanceof ParameterizedType) {
Type actualType = ((ParameterizedType) type).getActualTypeArguments()[0];
System.out.println(actualType);
}
当然,在一般情况下,您应该遍历数组,而不是假定数组有一个元素([0]
)。在上面的示例中,您可以转换actualType
为java.lang.Class
。在其他情况下,可能会有所不同(请参阅meriton的评论)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句