Reputation: 15984
I have a function that receives as parameter a json string and a class name as string of an object. The json is really a list of this object. I'm trying to create the list from the json but I'm unsuccessful.
Here is how I decode the json when the class name is known at compile time:
Type listOfObjects = new TypeToken<List<UsernamePart>>(){}.getType();
Gson gson = new Gson();
List<UsernamePart> parts = gson.fromJson(input, listOfObjects);
That works perfectly. But what happens if I want to do something like this:
// I have a string
String className = "UsernamePart";
// I can easily create a class object
Class<?> clazz = Class.forName(className);
// and now what?
Type listOfObjects = new TypeToken<List<??????????>>(){}.getType();
Gson gson = new Gson();
List<UsernamePart> parts = gson.fromJson(input, listOfObjects);
Upvotes: 4
Views: 439
Reputation: 2814
String className = "UsernamePart";
Class<?> genericClass = Class.forName(className);
Class arrayClass = java.lang.reflect.Array.newInstance(genericClass, 0).getClass();
Object[] array = (Object[]) new Gson().fromJson(input, arrayClass);
List parts = com.google.common.collect.Lists.newArrayList(array);
Upvotes: 3
Reputation:
Unfortunately you can not parameterize a Generic at runtime. The type must always been known at compile time.
Upvotes: 0