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

时间:2021-03-11 21:38:40
interface Foo<T> { ... }
class Bar implements Foo<Baz> { ... }

I've got a Bar object. How to get the value of T for 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.

到目前为止,我只得到了接口和T,但是我看不到它的值。

Thanks in advance.

提前谢谢。

2 个解决方案

#1


20  

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 actualType to java.lang.Class. In other cases it may be different (see comment by meriton)

当然,在一般情况下,您应该迭代数组,而不是假设它具有excatly[0]。通过上面的示例,您可以将actualType转换为java.lang.Class。在其他情况下可能会有所不同(参见meriton的评论)

#2


0  

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.

如果在类路径中已经有了番石榴,那么在根据类型而不是索引指定接口/超类时,这将更加健壮。

TypeToken<?> baz = TypeToken.of(Bar.class).resolveType(Foo.class.getTypeParameters()[0]);
System.out.println(baz.getRawType()); // class Baz

#1


20  

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 actualType to java.lang.Class. In other cases it may be different (see comment by meriton)

当然,在一般情况下,您应该迭代数组,而不是假设它具有excatly[0]。通过上面的示例,您可以将actualType转换为java.lang.Class。在其他情况下可能会有所不同(参见meriton的评论)

#2


0  

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.

如果在类路径中已经有了番石榴,那么在根据类型而不是索引指定接口/超类时,这将更加健壮。

TypeToken<?> baz = TypeToken.of(Bar.class).resolveType(Foo.class.getTypeParameters()[0]);
System.out.println(baz.getRawType()); // class Baz