简体   繁体   中英

When does JAXB generates @XmlElementRef and @XmlElement type of annotations?

This question has been asked a multiple times in different ways, but I have a query from a different perspective here. So let's take below example :

<xs:element name="Ric" type="String" nillable="true" minOccurs="0"/>

For above line in XSD the JAXB generated below code :

@XmlElementRef(name = "Ric", type = JAXBElement.class, required = false)
    protected JAXBElement<String> ric;

but for following xsd element,

<xs:element name="Ric" type="String" minOccurs="0"/>

I get,

 @XmlElement(name = "Ric")
    protected String ric;

I have read several explanations of the difference between @XmlElement vs @XmlElementRef but since I am very new to working with XSDs I could not understand what they are trying to say. All I could grasp was that for nillable="true" this is the case. Can someone please explain in a layman's language that why JAXB generated a parameter type for an element which has nillable="true" and minOccur="0" . I know we can do away with just one of these too, but client needs it this way.

jaxb version : 2.2.11

JAXB is all about mapping between Java and XML, in both directions.

So for a schema of:

<xs:element name="Ric" type="String" minOccurs="0"/>

a Java like:

protected String ric;  

with ric = null unambiguously maps to the absence of the "Ric" element (ie the parent element has zero "Ric" children elements).

But for a schema of:

<xs:element name="Ric" type="String" nillable="true" minOccurs="0"/>

you wouldn't know whether a String equal to 'null' maps to zero "Ric" elements or a "Ric" element with value xsi:nil . So you need the extra JAXBElement wrapper to differentiate.

See the accepted answer here .

Not sure my answer is any more easy to understand than that.. but maybe it helped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM