I can declare JAXB element in two ways:
@XmlElement
public int x;
or
private int x;
@XmlElement
public int getX(){...}
The first variant, AFAIK, creates getter, mapped to XML, anyway. What is the difference between these two ways?
It relates to the @XmlAccessorType
annotation.
XmlAccessType.PROPERTY
: Fields are bound to XML only when they are explicitly annotated by some of the JAXB annotations.
XmlAccessType.FIELD
: Getter/setter pairs are bound to XML only when they are explicitly annotated by some of the JAXB annotations
Update to explain based on comment:
Let's consider a simple xml that looks like this:
<root>
<value>someValue</value>
</root>
And we have a class:
@XmlRootElement(name = "root")
//@XmlAccessorType(XmlAccessType.PROPERTY)
@XmlAccessorType(XmlAccessType.FIELD)
public class DemoRoot {
@XmlElement
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
If you try to unmarshal using XmlAccessType.FIELD
and the @XmlElement
annotation above the field, then you will unmarshal fine.
If you use XmlAccessType.PROPERTY
you will receive the following error:
IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions Class has two properties of the same name "value"
This is because it takes into consideration both the explicitly annotated with @XmlElement
field 'value' and the getters/setters.
And vice versa if you move the @XmlElement
annotation on the getter/setter.
The use of @XMLElement (and similar annotations) before fields or before getters is well explained in this post: http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html.
The following annotation before a class determines the XML bindings of fields/getters: