Why doesn't JAXB generate setters for Lists

Here is the justification from the JAXB specification - page 60.

Design Note – There is no setter method for a List property. The getter returns the List by reference. An item can be added to the List returned by the getter method using an appropriate method defined on java.util.List. Rationale for this design in JAXB 1.0 was to enable the implementation to wrapper the list and be able to perform checks as content was added or removed from the List.

So if the implementation of the List was overriding add/remove to perform validation, replacing that 'special' List with (for instance) an ArrayList would defeat these checks.


Link for : No setter for list

The code in the getter method ensures that the List is created. There is no corresponding setter which means that all additions or deletions of list elements have to be made on the "live" list.

As the quote says that there is no setter as when you use the getter method it insures that a new instance of the list is initialized if not present.

And after that when you have to add or remove anything you will have to use

getElement3().add(Type);

UPDATE : Difference in marshalling for null and empty list

Example where list is null

@XmlRootElement(name = "list-demo")
public class ListDemo {

    @XmlElementWrapper(name = "list")
    @XmlElement(name = "list-item")
    private List<String> list;

}

OUTPUT will be

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<list-demo/>

Example where list is empty

@XmlRootElement(name = "list-demo")
public class ListDemo {

    @XmlElementWrapper(name = "list")
    @XmlElement(name = "list-item")
    private List<String> list = new ArrayList<String>();

}

OUTPUT will be:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<list-demo>
    <list/>
</list-demo>

Agree with Patrick's concern above. If I was coding to the generated java classes directly I'd be happy to oblige, but I'm using an introspective tool expects either a setter or a directly accessible member. Had success using a plugin to XJC from https://github.com/highsource/jaxb2-basics/wiki/JAXB2-Setters-Plugin and adding a -B-Xsetter argument to wsimport