users@jaxb.java.net

Re: JAXB Generic

From: Kenny MacLeod <kennym_at_kizoom.com>
Date: Fri, 26 Sep 2008 09:53:53 +0100

No problemo.

I can highly recommend The O'Reilly book on Java Generics. It's
extremely readable, and manages to explain neatly why many things in
generics are the way they are, e.g. why you can't create a generic
subclass of Exception.



Damon Goodyear wrote:
> Do you know that feeling when you sort of know the kind of answer to
> your question but don't know it detail? This is it. I would have
> pratted around for ages in the region of your answer and maybe got it,
> maybe not.
>
> As you say, annoying. Passing two lots of information when one should
> do....
>
> Thanks for the answer...
>
>
> Damon Goodyear
>
>
> ------------------------------------------------------------------------
> > Date: Thu, 25 Sep 2008 22:27:30 +0100
> > From: kennym_at_kizoom.com
> > To: users_at_jaxb.dev.java.net
> > Subject: Re: JAXB Generic
> >
> > > 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
> >
> >
> > ---------------------------------------------------------------------
> > To unsubscribe, e-mail: users-unsubscribe_at_jaxb.dev.java.net
> > For additional commands, e-mail: users-help_at_jaxb.dev.java.net
> >