I have this code I am refactoring:
if (response != null) {
Type collectionType = new TypeToken<List<GameInfo>>() {}.getType();
Gson gson = new Gson();
return (List<GameInfo>) gson.fromJson(response, collectionType);
}
Can I create a function where the “List” part could be any Collection type?
Example of illegal code:
private <T> T collectionFromJson(String pResponseJson, Class<T> pCollectionClass) {
T result = null;
Type collectionType = new TypeToken<pCollectionClass>() {
}.getType();
...
return result;
}
Example of illegal call to illegal code that illustrates what I’m shooting for:
return collectionFromJson(response, List<GameInfo>.class);
This isn’t going to be possible using a
Class<T>argument, sinceClassonly supports representing raw types likeList– the typeList<GameInfo>cannot be represented by aClassobject, which is whyTypeTokenexists.Your method would need to take a
TypeToken<T>argument instead and leave it up to the caller to create that argument:(disclaimer: I only have experience with Java/generics, not GSON)