users@jaxb.java.net

Re: JAXB Generic

From: Kenny MacLeod <kennym_at_kizoom.com>
Date: Thu, 25 Sep 2008 22:27:30 +0100

> JAXBContext ctx =
> JAXBContext.newInstance(T.class.getPackage().getName());

> ...except that the T.class line is jumped on by the compiler as being an
> illegal class literal for type parameter T. Also, the compiler moans
> about the casting of the object returned.

This is the big gotcha of java generics. At runtime, the information
about T is lost, so you can't use T.class.

You need to pass in another parameter to your method, which is the Class
object representing T:

public T load(String fileName, Class<? extends T> c){
    try{
       JAXBContext ctx = JAXBContext.newInstance(c.getPackage().getName());
       Unmarshaller u = ctx.createUnmarshaller();
       JAXBElement rootElement = (JAXBElement) u.unmarshal(new
FileInputStream(fileName));

       w = (T)rootElement.getValue();

    } catch (...)
    }
      return a;
    }

It's annoying, but unavoidable, but the caller of the method knows what
T is, so it can pass in the correct class.

As for the warning, you just have to live with it, or use @SuppressWarning


kenny