XoXo
XoXo

Reputation: 1599

Should no-arg constructor initialize fields in the context of jaxb?

Suppose we have this class for jaxb to serialize:

@XmlRootElement
public class Property {
    private String key;
    private Object value;

    public Property(String key, Object value) {
        this.key = key;
        this.value = value;
    }

    public Property() {
        // a no-arg default constructor is needed; 
        // otherwise, a "com.sun.xml.bind.v2.runtime.IllegalAnnotationsException" is thrown
    }
}

The question is for the no-arg constructor Property() :

Do we need to initialize the fields (key and value)? If so, what should they be?

Upvotes: 2

Views: 860

Answers (1)

bdoughan
bdoughan

Reputation: 149027

A JAXB implementation does not require that you initialize the fields. This would depend upon your use case.

Mapping to Fields

If you do not provider accessor methods for your fields then you should specify @XmlAccessorType(XmlAccessType.FIELD) on your class, so that JAXB will treat those fields as mapped.

Constructor

You could add a private constructor. This would meet JAXB's requirements and restrict access to it.

Immutable Fields

If the fields in your object was immutable then you could create an XmlAdapter for your class to handle this use case.

Upvotes: 2

Related Questions