Search code examples
javaxmljaxbmarshallingunmarshalling

What's the difference between JAXB annotations put on getter versus setters versus members?


Title says it all.

I would like to know what is the principial difference between putting JAXB annotation (like @XmlElement) on field / getter / setter. It seems to me that (in simple cases) it does not matter.

E.g. lets take this

class A  {
    private String a;

    public String getA() { return a; }

    public void setA(String a) { this.a = a; }
}

now it seems to me that it does not matter if I put @XmlElement on member field or on getter / setter. It just marshalls ok. Are there any usecases when I need to make difference and when it does matter?

When I go to unmarshall this (xml back to A) what JAXB does specifically?

I am using JAXB MOXy implementation

Thanks


Solution

  • By default JAXB impls will treat properties (get/set pairs), public fields (instance variables), and annotated non-public fields as mapped. If you just annotate a field you will get a duplicate mapped property exception.

    If you want to annotate the field you should specify @XmlAccessorType(XmlAccessType.FIELD) on the class.

    For More Information