users@jaxb.java.net

JAXB Generic

From: Damon Goodyear <damongoodyear_at_hotmail.com>
Date: Thu, 25 Sep 2008 21:39:48 +0100

I have a set of utilities for loading data from XML files that look like this--
public WidgetType loadWidget(){
   try{ JAXBContext ctx = JAXBContext.newInstance(WidgetType.class.getPackage().getName()); Unmarshaller u = ctx.createUnmarshaller(); JAXBElement rootElement = (JAXBElement) u.unmarshal(new FileInputStream("widget data.xml"));
 
      w = (WidgetType) rootElement.getValue(); } catch (...); }
 
   return w;
}
 
There are classes with load functions for Wadgets, Wedgets, Wodgets and Wudgets. All identical in form to the above. A classic case I would have thought for creating a generic that looks something like this--
 
public class XMLCodec<T> {
...
public T load(String fileName){
   try{ JAXBContext ctx = JAXBContext.newInstance(T.class.getPackage().getName()); Unmarshaller u = ctx.createUnmarshaller(); JAXBElement rootElement = (JAXBElement) u.unmarshal(new FileInputStream(fileName));
 
      w = (T)rootElement.getValue(); } catch (...)
   }
     return a;
   }
 
...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.
 
Unfortunately, my understanding of Java/OOP is limited at this level so I am not even able to formulate the right question to ask. If anyone can help me solve the problem (write a suitable generic) and suggest a place for further reading so that I don't have to ask in the first place it would be gratefully received.
 
Thanks,
 
D