在字段之前和在 getter 声明之前使用 @XmlElement 有什么区别? [英] What is the difference between using @XmlElement before field and before getter declaration?

查看:25
本文介绍了在字段之前和在 getter 声明之前使用 @XmlElement 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以通过两种方式声明 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.

这篇关于在字段之前和在 getter 声明之前使用 @XmlElement 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆