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?
Building on the previews answers from colleagues, just in case anybody is still looking for an answer.
I had the issue of having the root element of my scheme being defined as:
And therefore I was getting a Cast Exception at:
What I did was to change the first line of the try block to:
That resolved the problem for me.
I also encountered the "Javax.xml.bind.JAXBElement cannot be cast to" error and found this very simple solution:
Since, apparently, an object of type JAXBElement is returned, you need to typecast its value instead.
Source: https://forums.oracle.com/thread/1625944
Does
FooClass
have theXmlRootElement
annotation? If not, try:That's based on the Unofficial JAXB Guide.
Use JAXBIntrospector on the JAXBElement to get the schemaObject like >>
Refer: when does JAXB unmarshaller.unmarshal returns a JAXBElement<MySchemaObject> or a MySchemaObject?
Sometimes you have a XSD definition with multiple different root elements (for instance XSD defined in WSDL) and in that case the generated classes are missing @XmlRootElement. So as user mbrauh already wrote you have to get the value of JAXBElement. In my case I used:
So using generics you can easily avoid double type casting.
I ran into the same problem today, saw the answers here, did some research and looks to me that the most generic solution is to use JAXBIntrospector. Hence -
should be written as
Or even better, to make it more generic -