Type casting problem while unmarshalling XML objects using JAXB

While using JAXB to unmarshall objects from a given XML, a very common problem might occur which is the type casting of the unmarshalled object. For instance, for the following code:
JAXBContext jaxbContext = JAXBContext.newInstance("user.jaxb");
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
user.jaxb.Type myType = (user.jaxb.Type) unmarshaller.unmarshal(new File("myXML.xml"));
For the above code, the error: Exception in thread "main" java.lang.ClassCastException: javax.xml.bind.JAXBElement cannot be cast to user.jaxb.Type might occur.
The type of the object returned by the unmarshaller is JAXBElement and trying to typecast it to your resepective type directly causes the classcastexecption, whereas, if you get the value of the returned JAXBElement object by calling the .getValue( ) method, and then do the type casting on this object to your respective type, the problem is solved,  as follows:
user.jaxb.Type myType = (user.jaxb.Type)((javax.xml.bind.JAXBElement) unmarshaller.unmarshal(new File("myXML.xml"))).getValue();
I hope it helps.

Comments

Jayashree Phule said…
Nice article...
Thanks for help... :)

Jayashree.
Zavier said…
Thank you! Was beating my head on this for an hour!
BT said…
4 years later I have to thank you. I was scratching my head over this for a day long. Thanks bro.
Unknown said…
thank you on 2015. :-)
nitin....pvpsit said…
Dude .. thank you so much... i think this is my first comment in last 2 years... really really mean it.....
Unknown said…
I know it's an old post but you sir just saved my life :). Thank you very much.
Unknown said…
As above. Nearly 6 years on, this post is still saving lives.
Thank you!
Pao said…
Now i can beat my deadline!!! Maraming Salamat! Thank you!
joe said…
Excellent, it worked.
Faraz Rafi said…
I am glad it helped you all :)
thomas said…
hell yeah you saved me, thanks a lot man
Gus said…
2017 and still saving lifes :D
Anonymous said…
Thanks alot man...my prob solved
mmella said…
Great, thanks a lot !!!
spring said…
收益匪浅 ,非常感谢
K Vinod said…
Thanks and Awesome keep it up...!
Anonymous said…
10 years later and this is still helping out!

Thats the nature of dealing with iffy 3rd party XML you have no control over.
Navaneethan said…
Good article, helped solving the issue. Thank you!!!

Popular posts from this blog

Second Interview at Seattle, Microsoft HQ (Part I)

My J2EE/Component Based Software Design Projects