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)...

Comments