如何使用TypeToken获取类型参数? [英] How to use TypeToken to get type parameter?

查看:84
本文介绍了如何使用TypeToken获取类型参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在运行时使用 TypeToken Guava文档 example IKnowMyType

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());
    }
}

当我运行这段代码时,得到类java.lang.Enum 作为输出。为什么不是没有得到 class MyEnum 而不是?

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

推荐答案

不能用于运行时类型的值 Test

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

Java无法传播类型在$ Test class在这里实例化时推断的参数

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()) {
};

因此 TypeToken 不知道什么 E 应该引用。

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

Javadoc 声明


在解析上下文中的自由类型变量
的同时,构造一个新的类型标记 T declaringClass

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>() {
};

现在,因为类保持有关它们的通用超类的信息,所以 getClass <上面的 TypeToken 实例中的code>调用为 E 解释为 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.

这篇关于如何使用TypeToken获取类型参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆