tags:

views:

1341

answers:

4

Hi,

Trying to get past a class cast exception here:

FooClass fooClass = (FooClass ) unmarshaller.unmarshal(inputStream);

throws this exception:

java.lang.ClassCastException: javax.xml.bind.JAXBElement

I don't understand this - as the class was generated by the xjc.bat tool - and the classes it generated I have not altered at all - so there should be no casting problems here - the unmarshaller should really be giving me back a class that CAN be cast to FooClass.

Any ideas as to what I am doing wrong?

+1  A: 

Are you absolutely sure FooClass is the root element of the xml input source you passed it? Unmarshall will return an object of the root element created by xjc.

Greg Noe
+4  A: 

Does FooClass have the XmlRootElement annotation? If not, try:

JAXBElement<FooClass> root = unmarshaller.unmarshal(inputStream, 
                                                    FooClass.class);
FooClass foo = root.getValue();

That's based on the Unofficial JAXB Guide.

Jon Skeet
Why has the JAXB compiler not put an XmlRootElement annotation in my class in the first place - as I cannot find one. Your code works - but I would like to know more - i.e. why does it work?
Vidar
Pass - I only investigated far enough to solve the original problem :) I don't really know a lot about JAXB...
Jon Skeet
Fair do's - but thanks for helping me out anyway.
Vidar
+2  A: 

I'd look at the XML file and make sure it is roughly what you expect to see.

I'd also temporarily change the code to:

Object o = unmarshaller.unmarshal(inputStream);
System.out.println(o.getClass());

If the first one failes then the class cast is happening inside the unmarshal method, if it succeeds then you can see the actual class that you are getting back and then figure out why it isn't what you expect it to be.

TofuBeer
+3  A: 

For a fuller explanation read the following link.

It turns out that your XSD must be properly set up - ie there must be some root element encompassing all the other elements.

Vidar