Thursday, August 23, 2007

A JAXB Problem
JAXBContext jc = JAXBContext.newInstance("edu.iu.cgl.gpir");
Unmarshaller u = jc.createUnmarshaller();
ResourceStatic rs = (ResourceStatic)u.unmarshal(new StreamSource(new StringReader(rslt)));

The above method works fine for GPIR while got an error for QBETS:
Exception in thread "main" java.lang.ClassCastException: javax.xml.bind.JAXBElement cannot be cast to edu.ucsb.cs.nws.MachinesType

I debugged and found that the returned value of unmarshal() is JAXBElement, but don't know why it can't be cast to the type I expect.

Found the solution at http://www.velocityreviews.com/forums/t298335-javalangclasscastexception-javaxxmlbindjaxbelement.html

Use
MachinesType machines = (MachinesType)((JAXBElement)u.unmarshal(new StreamSource(new StringReader(rslt)))).getValue();

It works.

3 comments:

Unknown said...

Thank you, Gong.

It also worked for me, although there are situations when casting to JAXBElement is not necessary. For instance, when I use (unnamed) complexType definition inside my element definition, unmarshalling returns desired type.

Regards,
Ognjen

Konstantin Galileyev said...

Thank you, it really helped.

Phillip Gibb said...

Shot, that solved my problem as well :-)