Reputation: 13517
I'm trying to get a json array to deserliaze when using generics, see my work below:
public class Lookup<T extends Profile> {
protected final Class<T> getSuperClass() {
ParameterizedType superClass = (ParameterizedType)this.getClass().getGenericSuperclass();
return (Class<T>)(superClass.getActualTypeArguments().length == 0 ? BasicProfile.class : superClass.getActualTypeArguments()[0]);
}
protected final Class<T[]> getSuperClassArray() {
ParameterizedType superClass = (ParameterizedType)this.getClass().getGenericSuperclass();
return (Class<T[]>)(superClass.getActualTypeArguments().length == 0 ? BasicMojangProfile[].class : superClass.getActualTypeArguments());
}
public void doWork() { // This Works
String jsonText = "{id=3, name=Derp}";
T result = new Gson().fromJson(jsonText, this.getSuperClass());
// Will be whatever T is (defined elsewhere), unless this class
// is created without a super class then properly defaults to
// the BasicProfile
}
public void doArrayWork() { // DOES NOT WORK
String jsonText = "[{id=3, name=Derp}]";
T[] result = new Gson().fromJson(jsonText, ?);
// Have tried the following (in place of the ?):
// new TypeToken<T>(){}.getType()
// new TypeToken<T[]>(){}.getType()
// new TypeToken<List<T>>(){}.getType() // with List<T> result
// this.getSuperClassArray()
}
}
How can I get doArrayWork to function properly? I do not want to pass whatever T is as a parameter to the method.
Upvotes: 1
Views: 126
Reputation: 18834
You can use Array.newInstance(this.getSuperClass(), 0).getClass()
.
This creates a array based on the class passed to the method, then it calls getCLass()
on that array to get the real class object representing that array.
Upvotes: 2