Search code examples
javajaxb2

How get class for a Generics class?


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?


Solution

  • Not the way you are trying to. This is due to type-erasure. At runtime all Ts 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;
       }
    }