问题描述
我可以通过两种方式声明 JAXB 元素:
I can declare JAXB element in two ways:
@XmlElement public int x;
或
private int x; @XmlElement public int getX(){...}
第一个变体,AFAIK,创建 getter,映射到 XML,无论如何.这两种方式有什么区别?
The first variant, AFAIK, creates getter, mapped to XML, anyway. What is the difference between these two ways?
推荐答案
与@XmlAccessorType注解有关.
XmlAccessType.PROPERTY :字段仅在被某些 JAXB 注释显式注释时才绑定到 XML.
XmlAccessType.PROPERTY : Fields are bound to XML only when they are explicitly annotated by some of the JAXB annotations.
XmlAccessType.FIELD:只有在某些 JAXB 注释明确注释时,Getter/setter 对才绑定到 XML
XmlAccessType.FIELD: Getter/setter pairs are bound to XML only when they are explicitly annotated by some of the JAXB annotations
根据评论更新解释:
让我们考虑一个如下所示的简单 xml:
Let's consider a simple xml that looks like this:
<root> <value>someValue</value> </root>
我们有一个类:
@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; } }
如果您尝试使用 XmlAccessType.FIELD 和字段上方的 @XmlElement 注释来解组,那么您将可以很好地解组.
If you try to unmarshal using XmlAccessType.FIELD and the @XmlElement annotation above the field, then you will unmarshal fine.
如果您使用 XmlAccessType.PROPERTY,您将收到以下错误:
If you use XmlAccessType.PROPERTY you will receive the following error:
IllegalAnnotationsException: 1 计数 IllegalAnnotationExceptions 类有两个同名的属性值"
IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions Class has two properties of the same name "value"
这是因为它考虑了显式注释的 @XmlElement 字段值"和 getter/setter.
This is because it takes into consideration both the explicitly annotated with @XmlElement field 'value' and the getters/setters.
如果您将 @XmlElement 注释移动到 getter/setter 上,反之亦然.
And vice versa if you move the @XmlElement annotation on the getter/setter.