Unmarshalling collections in JaxB

Stas picture Stas · Jun 23, 2009 · Viewed 19.4k times · Source

suppose I have this class:

public class A {

    private HashMap<String, B> map;

    @XmlElement
    private void setB(ArrayList<B> col) {
        ...
    }

    private ArrayList<B> getB() {
        ...
    }

}

When trying to unmarshall an xml document to this class using JaxB I notice that instead of calling the setB() method and sending me the list of B instances JaxB actually calls the getB() and adds the B instances to the returned list. Why?

The reason I want the setter to be called is that the list is actually just a temporary storage from which I want to build the map field, so I thought to do it in the setter.

Thanks.

Answer

silmx picture silmx · Jun 23, 2009

thats the way jaxb is handling collections. you have to be sure you have a non null collection when jaxb try to unmarshal.

there is a plugin (never used it myself) but can be helpful: https://jaxb2-commons.dev.java.net/collection-setter-injector/