I'm trying to create a generics class for de-/serializing via JAXB. When creating the JAXBContext
a class has to be passed in, but of course with a generic class, this is not known in advance.
So when I try this I get a compilation error of course.
public class ServerSerializing<T>
{
private JAXBContext mJAXBContext = null;
public JAXBContext getJAXBContext()
{
if(mJAXBContext == null)
mJAXBContext = JAXBContext.newInstance(T.class);
return mJAXBContext;
}
}
Results in:
Illegal class literal for the type parameter T
So is there a way this can be done with a generic?
Not the way you are trying to. This is due to type-erasure. At runtime all T
s are converted to Object
. So in your solution you would always be creating just an Object
not a T
. The solution is to pass in a class
instance to the generic's constructor.
public class ServerSerializing<T>
{
private JAXBContext mJAXBContext = null;
private final Class<T> type;
public ServerSerializing(Class<T> type){
this.type = type;
}
public JAXBContext getJAXBContext()
{
if(mJAXBContext == null)
mJAXBContext = JAXBContext.newInstance(type);
return mJAXBContext;
}
}