Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

java - What is the difference between using @XmlElement before field and before getter declaration?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...