when does JAXB unmarshaller.unmarshal returns a JAXBElement or a MySchemaObject?

后端 未结 5 979
日久生厌
日久生厌 2020-12-29 20:41

I have two codes, in two different java projects, doing almost the same thing, (unmarshalling the input of a webservice according to an xsd-file).

But in one case I

5条回答
  •  伪装坚强ぢ
    2020-12-29 21:05

    If the root element uniquely corresponds to a Java class then an instance of that class will be returned, and if not a JAXBElement will be returned.

    If you want to ensure that you always get an instance of the domain object you can leverage the JAXBInstrospector. Below is an example.

    Demo

    package forum10243679;
    
    import java.io.StringReader;
    import javax.xml.bind.*;
    import javax.xml.transform.stream.StreamSource;
    
    public class Demo {
    
        private static final String XML = "";
    
        public static void main(String[] args) throws Exception {
            JAXBContext jc = JAXBContext.newInstance(Root.class);
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            JAXBIntrospector jaxbIntrospector = jc.createJAXBIntrospector();
    
            Object object = unmarshaller.unmarshal(new StringReader(XML));
            System.out.println(object.getClass());
            System.out.println(jaxbIntrospector.getValue(object).getClass());
    
            Object jaxbElement = unmarshaller.unmarshal(new StreamSource(new StringReader(XML)), Root.class);
            System.out.println(jaxbElement.getClass());
            System.out.println(jaxbIntrospector.getValue(jaxbElement).getClass());
        }
    
    }
    

    Output

    class forum10243679.Root
    class forum10243679.Root
    class javax.xml.bind.JAXBElement
    class forum10243679.Root
    

提交回复
热议问题