Why and when JAXBElement is required in JAXB?

There are a few use cases where a JAXBElement is required:

  1. An element is both nillable="true" and minOccurs="0". In this case what does null on the mapped field/property mean? When the property is JAXBElement a null value means the element isn't present and a JAXBElement wrapping null means an XML element with xsi:nil="true".
  2. There are 2 global elements with the same named complex type. Since in JAXB classes correspond to complex types a way is needed to capture which root element was encountered. For more details see this article I wrote.
  3. There is a choice structure where either foo or bar elements can occur and they are the same type. Here a JAXBElement is required because simply encountering a String value isn't enough to indicate which element should be marshalled.
  4. An element with xsi:nil is encountered in the document that contains attributes. In this example the object corresponding to that element can still be unmarshalled to hold the attribute values, but JAXBElement can stil indicate that the element was null.

JAXBElement is used to preserve the element name/namespace in use cases where enough information is not present in the object model. It's often used with substitution groups.

Without any JAXB metada the result will be wrapped in a JAXBElement. You can eliminates the root level JAXBElement by using the @XmlRootElement annotation.

If you use xsd files from an external source and no XmlRootElement annotation is available on the generated classes, using JAXBElement during the marshalling process can really come in handy since you can unmarshal the xml to an object using the JAXBElement wrapper. You will see that specifying the class itself doesn't work in that case...

This will work:

JAXBElement<Object> je = (JAXBElement<Object>) unmarshaller.unmarshal(objectXML);
Object = je.getValue();

This will throw a JAXBException:

Object obj = (Object) unmarshaller.unmarshal(objectXML);