Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy doesn't JAXB generate setters for Lists
    text
    copied!<p>When I generate JAXB classes from an XSD, the elements with <code>maxOccurs="unbounded"</code> gets a getter method generated for them, but no setter method, as follows:</p> <pre><code>/** * Gets the value of the element3 property. * * &lt;p&gt; * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a &lt;CODE&gt;set&lt;/CODE&gt; method for the element3 property. * * &lt;p&gt; * For example, to add a new item, do as follows: * &lt;pre&gt; * getElement3().add(newItem); * &lt;/pre&gt; * * * &lt;p&gt; * Objects of the following type(s) are allowed in the list * {@link Type } * * */ public List&lt;Type&gt; getElement3() { if (element3 == null) { element3 = new ArrayList&lt;Type&gt;(); } return this.element3; } </code></pre> <p>The method comment makes it crystal clear on how can I use it, but my question is as follows: <br><strong>Why doesn't JAXB just generate a setter, following the Java Beans rules?</strong> I know I can write the setter method myself, but is there any advantage to the approach suggested in the generated getter method?</p> <p>This is my XSD:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://www.example.org/DoTransfer/" targetNamespace="http://www.example.org/DoTransfer/"&gt; &lt;element name="CollectionTest" type="tns:CollectionTest"&gt;&lt;/element&gt; &lt;complexType name="CollectionTest"&gt; &lt;sequence&gt; &lt;element name="element1" type="string" maxOccurs="1" minOccurs="1"&gt;&lt;/element&gt; &lt;element name="element2" type="boolean" maxOccurs="1" minOccurs="1"&gt;&lt;/element&gt; &lt;element name="element3" type="tns:type" maxOccurs="unbounded" minOccurs="1" nillable="true"&gt;&lt;/element&gt; &lt;/sequence&gt; &lt;/complexType&gt; &lt;complexType name="type"&gt; &lt;sequence&gt; &lt;element name="subelement1" type="string" maxOccurs="1" minOccurs="1"&gt;&lt;/element&gt; &lt;element name="subelement2" type="string" maxOccurs="1" minOccurs="0"&gt;&lt;/element&gt; &lt;/sequence&gt; &lt;/complexType&gt; &lt;/schema&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload