java 如何使用java反射获取类型参数值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3609799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get type parameter values using java reflection?
提问by mik01aj
interface Foo<T> { ... }
class Bar implements Foo<Baz> { ... }
I've got a Barobject. How to get the value of Tfor it (Baz)?
我有Bar对象 如何获得它的值T( Baz)?
So far, I only managed to get the interface and T, but I can't see a way to get its value.
到目前为止,我只设法获得了接口 and T,但我看不到获得其价值的方法。
Thanks in advance.
提前致谢。
回答by Bozho
Type type = bar.getClass().getGenericInterfaces()[0];
if (type instanceof ParameterizedType) {
Type actualType = ((ParameterizedType) type).getActualTypeArguments()[0];
System.out.println(actualType);
}
Of course, in the general case, you should iterate over the array, rather than assuming it has excatly one element ([0]). With the above example, you can cast actualTypeto java.lang.Class. In other cases it may be different (see comment by meriton)
当然,在一般情况下,您应该遍历数组,而不是假设它只有一个元素 ( [0])。使用上面的示例,您可以强制转换actualType为java.lang.Class. 在其他情况下可能会有所不同(请参阅meriton的评论)
回答by Dan Godfrey
If you already have Guava on the classpath, this is a bit more robust as you specify the interface/superclass by type rather than index.
如果您已经在类路径上安装了 Guava,那么当您按类型而不是索引指定接口/超类时,这会更健壮一些。
TypeToken<?> baz = TypeToken.of(Bar.class).resolveType(Foo.class.getTypeParameters()[0]);
System.out.println(baz.getRawType()); // class Baz

