views:

107

answers:

1
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 in advance.

+9  A: 
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)

Bozho
Note that in general, `actualType` is not necessarily a plain `java.lang.Class` - it could also be a `GenericArrayType`, a `ParametrizedType`, or a `TypeVariable`.
meriton
True. I meant that in his case it's `Class`.
Bozho