我有这个代码我正在重构:
if (response != null) {
Type collectionType = new TypeToken<List<GameInfo>>() {}.getType();
Gson gson = new Gson();
return (List<GameInfo>) gson.fromJson(response, collectionType);
}
我可以创建一个“List”部分可以是任何Collection类型的函数吗?
非法代码示例:
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);
答案 0 :(得分:2)
使用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 / generics的经验,而不是GSON)