Search code examples
javaxmlxsdjaxb

Java java.lang.ClassCastException: javax.xml.bind.JAXBElement cannot be cast exception when code generated using IntelliJ


I have created Java objects from XSD using IntelliJ Tools > JAXB > Generate Java Code From XML Schema using JAXB...

I am basically trying to generate Java objects from the XSD and then read a XML which would be compliant with this XSD into Java objects.

For my exercise, I am using the XSD from the six group website related to Credit Transfer Version 1.10.

However, when I try to run following code I see an exception : Java.lang.ClassCastException: javax.xml.bind.JAXBElement cannot be cast

public class Pain001Tester {

    public static void main(String[] args) throws IOException {

        String fileName = "pain_001_Beispiel_1.xml";
        ClassLoader classLoader = new Pain001Tester().getClass().getClassLoader();

        File file = new File(classLoader.getResource(fileName).getFile());

        //File is found
        System.out.println("File Found : " + file.exists());

        //Read File Content
        String content = new String(Files.readAllBytes(file.toPath()));
        System.out.println(content);


        JAXBContext jaxbContext;
        try
        {
            jaxbContext = JAXBContext.newInstance(ObjectFactory.class);

            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

            ObjectFactory xmlMessage = (ObjectFactory) jaxbUnmarshaller.unmarshal(new StringReader(content));
            //ObjectFactory xmlMessage = (ObjectFactory) JAXBIntrospector.getValue(jaxbUnmarshaller.unmarshal(new StringReader(content)));

            //JAXBElement<ObjectFactory> userElement = (JAXBElement<ObjectFactory>) jaxbUnmarshaller.unmarshal(new StringReader(content));
            //ObjectFactory user = userElement.getValue();

            System.out.println(xmlMessage);
        }
        catch (JAXBException e)
        {
            e.printStackTrace();
        }

    }
}

I think my issue is related to XMLRootElement but not sure if this is the issue. I understand the following stackoverflow question comes close to my problem but was not able to resolve my problem using couple of solutions highlighted in the stackoverflow case : No @XmlRootElement generated by JAXB


Solution

  • I assume the error occurs in

    ObjectFactory xmlMessage = (ObjectFactory) jaxbUnmarshaller.unmarshal(new StringReader(content));
    

    jaxbUnmarshaller.unmarshal() does not return a ObjectFactoryt type, so you cannot cast the result to ObjectFactory. It returns a instance of the generated class which corresponds to the root element of the xml file.