Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

java - How to use TypeToken to get type parameter?

I am attempting to look up a type parameter at runtime using TypeToken as showing in the Guava documentation example IKnowMyType:

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

    private static enum MyEnum {
        FIRST,
        SECOND
    };

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

    public static void main(String[] args) {
        Test<MyEnum> container = new Test<>();
        System.out.println(container.enumType.getRawType());
    }
}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...