在字段和 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 创建了 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
:Getter/setter 对只有在被某些 JAXB 注释显式注释时才绑定到 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 counts of 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.
反之亦然,如果您在 getter/setter 上移动 @XmlElement
注释.
And vice versa if you move the @XmlElement
annotation on the getter/setter.
这篇关于在字段和 getter 声明之前使用 @XmlElement 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!