【发布时间】:2014-10-01 07:49:08
【问题描述】:
我在我的项目中使用 Guava TypeToken 类,但我得到了意想不到的结果。
我有MyGenericClass<T>:
public class MyGenericClass<T> implements MyInterface {
private TypeToken<T> recordType;
public MyGenericClass(String name) {
this.recordType = new TypeToken<T>(getClass()) {};
// ...
}
// ...
@SuppressWarnings("unchecked")
protected Class<T> getRecordType() {
return (Class<T>) recordType.getRawType();
}
}
因此,如果我通过new MyGenericClass<String>() 实例化一个对象,然后调用getRecordType(),我希望得到java.lang.String,而不是得到java.lang.Object。
但是,如果我扩展泛型类:
public class MyStringImpl extends MyGenericClass<String> {
// ...
}
并实例化这个新类:new MyStringImpl() 然后我得到正确的结果。
为什么会这样?这是TypeToken 的预期行为吗?
【问题讨论】:
-
“这是 TypeToken 的预期行为吗?” 是的。