Java 番石榴TypeToken和泛型类
我在我的项目中使用了番石榴类,但是我得到了一个意想不到的结果 我有Java 番石榴TypeToken和泛型类,java,generics,guava,Java,Generics,Guava,我在我的项目中使用了番石榴类,但是我得到了一个意想不到的结果 我有MyGenericClass: new MyGenericClass<String>() {} 并实例化这个新类:newmystringimpl(),然后得到正确的结果 为什么会这样?这是TypeToken的预期行为吗?要实现这一点,您需要在实例化MyGenericClass时使用相同的匿名子类技巧: new MyGenericClass<String>() {} newMyGenericClass()
MyGenericClass
:
new MyGenericClass<String>() {}
并实例化这个新类:newmystringimpl()
,然后得到正确的结果
为什么会这样?这是
TypeToken
的预期行为吗?要实现这一点,您需要在实例化MyGenericClass
时使用相同的匿名子类技巧:
new MyGenericClass<String>() {}
newMyGenericClass(){}
如果这样做,您将得到getRecordType
返回的String
。这是必要的原因已在中解释
客户端创建一个空的匿名子类。这样做会将类型参数嵌入到匿名类的类型层次结构中,这样我们就可以在运行时重建它,而不用考虑擦除
在Ian的回答中添加一些令人厌烦的细节:如果
TypeToken
按照您期望的方式工作,那就太好了,但这是不可能的。当你申报时
public class MyGenericClass<T> implements MyInterface {...}
public class MyStringImpl extends MyGenericClass<String> {...}
公共类MyGenericClass实现MyInterface{…}
JVM会看到类似这样的情况
public class MyGenericClass<Object> implements MyInterface {...}
公共类MyGenericClass实现MyInterface{…}
由于擦除
但是当你申报时
public class MyGenericClass<T> implements MyInterface {...}
public class MyStringImpl extends MyGenericClass<String> {...}
公共类MyStringImpl扩展了MyGenericClass{…}
然后在MyStringImpl
的定义中,记录使用的泛型,并可通过以下方式获得。这就是TypeToken
“这是TypeToken的预期行为吗?”是的,是的。