Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class Cast Exception when trying to unmarshall xml?

Tags:

java

jaxb

jaxb2

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?

like image 964
Vidar Avatar asked Apr 01 '09 19:04

Vidar


People also ask

What causes a class cast exception?

Introduction. ClassCastException is a runtime exception raised in Java when we try to improperly cast a class from one type to another. It's thrown to indicate that the code has attempted to cast an object to a related class, but of which it is not an instance.

What would cause an exception to be thrown from a cast?

A class cast exception is thrown by Java when you try to cast an Object of one data type to another.

How do you avoid ClassCastException in your code?

To prevent the ClassCastException exception, one should be careful when casting objects to a specific class or interface and ensure that the target type is a child of the source type, and that the actual object is an instance of that type.

What is Unmarshal exception?

This exception indicates that an error has occurred while performing an unmarshal operation that prevents the JAXB Provider from completing the operation. The ValidationEventHandler can cause this exception to be thrown during the unmarshal operations.


1 Answers

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

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

That's based on the Unofficial JAXB Guide.

like image 170
Jon Skeet Avatar answered Oct 03 '22 17:10

Jon Skeet