0

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?

Andrew Thompson
  • 163,965
  • 36
  • 203
  • 405
Devolus
  • 20,356
  • 11
  • 56
  • 104
  • This [has](http://stackoverflow.com/questions/182636/how-to-determine-the-class-of-a-generic-type) [been](http://stackoverflow.com/questions/3437897/how-to-get-class-instance-of-generics-type-t) [asked](http://stackoverflow.com/questions/4837190/java-generics-get-class) [before](http://stackoverflow.com/questions/3403909/get-generic-type-of-class-at-runtime) – DannyMo Jun 17 '13 at 18:18
  • How is it still possible to be doing Java and still not know about type erasure? Class tokens as the workaround are hardly a new idea. – scottb Jun 17 '13 at 18:20
  • @JohnB, thanks! I tried to find a solution first, but apparently I didn't use the correct keywords. – Devolus Jun 17 '13 at 18:28

1 Answers1

6

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;
   }
}
John B
  • 30,460
  • 6
  • 67
  • 92