Reputation: 10530
All,
I would like to pass in a class type as a variable, and use it to parametrize a list. For instance, I have my method as follows:
public void index(String url, Class clazz) {
Gson gson = new Gson();
Type listType = new TypeToken<List<clazz>>(){}.getType();
gson.fromJson(response.body().toString(), listType);
}
Is this even possible? Note that in this case, I can't use generics.
Upvotes: 2
Views: 875
Reputation: 72874
Class
is a raw type. Use it with a type parameter defined in a generic method and use that type parameter:
public <T> void index(String url, Class<T> clazz) {
Gson gson = new Gson();
Type listType = new TypeToken<List<T>>(){}.getType();
gson.fromJson(response.body().toString(), listType);
}
Upvotes: 2