开发者

How to get type parameter values using java reflection?

开发者 https://www.devze.com 2023-01-14 18:59 出处:网络
interface Foo<T> { ... } class Bar implements Foo<Baz> { ... } I\'ve got a Bar object. How to get the value of T for it (Baz)?
interface Foo<T> { ... }
class Bar implements Foo<Baz> { ... }

I've got a Bar object. How to get the value of T for it (Baz)?

So far, I only managed to get the interface and T, but I can't see a way to get its value.

Thanks i开发者_开发知识库n advance.


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)


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
0

精彩评论

暂无评论...
验证码 换一张
取 消