在字段之前和getter声明之前使用@XmlElement有什么区别? [英] What is the difference between using @XmlElement before field and before getter declaration?
问题描述
我可以用两种方式声明JAXB元素:
I can declare JAXB element in two ways:
@XmlElement
public int x;
或
private int x;
@XmlElement
public int getX(){...}
第一个变体AFAIK无论如何都会创建映射到XML的getter。这两种方式有什么区别?
The first variant, AFAIK, creates getter, mapped to XML, anyway. What is the difference between these two ways?
推荐答案
它与 @XmlAccessorType
注释有关。
-
XmlAccessType.PROPERTY
:字段仅在明确注释时才绑定到XML一些JAXB注释。
XmlAccessType.PROPERTY
: Fields are bound to XML only when they are explicitly annotated by some of the JAXB annotations.
XmlAccessType.FIELD
:Getter / setter对仅绑定到XML当它们被一些JAXB注释明确注释时
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:IllegalAnnotationExceptions的1个计数类有两个同名的属性value
IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions Class has two properties of the same name "value"
这是因为它同时考虑了明确注释的两个 @XmlElement
字段'value'和getters / setters。
This is because it takes into consideration both the explicitly annotated with @XmlElement
field 'value' and the getters/setters.
反之亦然,如果移动<$ c getc / setter上的$ c> @XmlElement 注释。
And vice versa if you move the @XmlElement
annotation on the getter/setter.
这篇关于在字段之前和getter声明之前使用@XmlElement有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!