我见过许多其他类似的问题,但我认为在这些问题之上还有一定程度的抽象会有所不同。即,我有一个带有静态泛型包装方法的实用程序类来反序列化泛型类型的对象(在构建时未知):
public final class Utils {
public static final Gson sGson = new Gson();
public static synchronized <T> T fromJson(String doc) {
return sGson.fromJson(doc, new TypeToken<T>(){}.getType());
}
}
一个简单的类来测试它:
public class TestDocument {
public TestDocument(String test) {
this.test = test;
}
public String test;
}
这很好用:
assertEquals(
new TestDocument("test").test,
((TestDocument) Utils.sGson.fromJson(
"{\"test\": \"test\"}",
new TypeToken<TestDocument>(){}.getType())).test);
但是,虽然静态通用实用程序方法没有,但看起来像调用它的等效方法:
assertEquals(
new TestDocument("test").test,
Utils.<TestDocument>fromJson("{\"test\": \"test\"}").test);
引发以下异常:
java.lang.ClassCastException:com.google.gson.internal.LinkedTreeMap 无法转换为 TestDocument
有没有办法通过通用方法使其工作?
江户川乱折腾
一只萌萌小番薯
婷婷同学_
相关分类