The accepted answer to this question describes how to create an instance of T
in the Generic
class. This involves passing in a Class<
W may not be available due to type erasure. You should require that a Class<W>
is passed into the method. You get a class object and its generic ensures that only W
and no subclass is passed in, due to covariance.
public InputField(String labelText, Class<W> cls)
{
super(new String[] {labelText}, cls);
}
will take W.class
but not WSubtype.class
.
Using .class
on a type parameter isn't allowed - because of type erasure, W
will have been erased to Component
at runtime. InputField
will need to also take a Class<W>
from the caller, like InputFieldArray
:
public InputField(String labelText, Class<W> clazz)
{
super(new String[] {labelText}, clazz);
}
If you're using the GSON
library, you can get the type of T
easily by using TypeToken
. The class documentation is available here:
I did it like this:
This is my class definition:
public class ManagerGeneric <T> {}
This is in my method:
// Get the type of generic parameter
Type typeOfT = new TypeToken<T>(){}.getType();
// Deserialize
T data = gson.fromJson(json, typeOfT);