Gili Gili - 1 year ago 132
Java Question

How to use TypeToken to get type parameter?

I am attempting to look up a type parameter at runtime using

as showing in the Guava documentation example

public class Test<E extends Enum<E>> {

private static enum MyEnum {

private final TypeToken<E> enumType = new TypeToken<E>(getClass()) {

public static void main(String[] args) {
Test<MyEnum> container = new Test<>();

When I run this code, I get
class java.lang.Enum
as output. Why am not not getting
class MyEnum

Answer Source

This "hack" won't work on a value of runtime type Test.

There's no way for Java to propagate the type argument inferred when instantiating your Test class here

Test<MyEnum> container = new Test<>();

down to the declaration

private final TypeToken<E> enumType = new TypeToken<E>(getClass()) {

And therefore the TypeToken has no idea what the E should refer to.

The Javadoc states

Constructs a new type token of T while resolving free type variables in the context of declaringClass.

Clients create an empty anonymous subclass. Doing so embeds the type parameter in the anonymous class's type hierarchy so we can reconstitute it at runtime despite erasure.

So that's what you need to do.

Test<MyEnum> container = new Test<MyEnum>() {

Now, because classes maintain information about their generic superclasses, the getClass call in the TypeToken instantiation above provides enough context for the E to be interpreted as MyEnum.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download