我正在重构这段代码:
if (response != null) {
Type collectionType = new TypeToken<List<GameInfo>>() {}.getType();
Gson gson = new Gson();
return (List<GameInfo>) gson.fromJson(response, collectionType);
}
我可以创建一个函数,其中“列表”部分可以是任何集合类型吗?
非法代码示例:
private <T> T collectionFromJson(String pResponseJson, Class<T> pCollectionClass) {
T result = null;
Type collectionType = new TypeToken<pCollectionClass>() {
}.getType();
...
return result;
}
非法调用非法代码的示例说明了我的目标:
return collectionFromJson(response, List<GameInfo>.class);
最佳答案
使用 Class<T>
是不可能实现这一点的参数,因为 Class
仅支持表示原始类型,如 List
- 类型List<GameInfo>
不能用 Class
表示对象,这就是为什么 TypeToken
存在。
您的方法需要采用 TypeToken<T>
相反,将其留给调用者来创建该参数:
private <T extends Collection<U>, U> T collectionFromJson(String pResponseJson, TypeToken<T> typeToken) {
return (T)new Gson().fromJson(pResponseJson, typeToken.getType());
}
...
TypeToken<List<GameInfo>> typeToken = new TypeToken<List<GameInfo>>() { };
List<GameInfo> lst = collectionFromJson(response, typeToken);
(免责声明:我只有 Java/泛型经验,没有 GSON)
关于java - 通过参数指定泛型类型信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10587500/