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

前端 未结 2 884
春和景丽
春和景丽 2020-12-07 06:39

I can declare JAXB element in two ways:

@XmlElement
public int x;

or

private int x;

@XmlElement
public int getX(){...}


        
相关标签:
2条回答
  • 2020-12-07 07:01

    The use of @XMLElement (and similar annotations) before fields or before getters is well explained in this post: http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html.

    The following annotation before a class determines the XML bindings of fields/getters:

    • @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER): public fields, annotated fields and properties
    • @XmlAccessorType(XmlAccessType.PROPERTY): annotated fields and properties
    • @XmlAccessorType(XmlAccessType.FIELD): fields and annotated properties
    • @XmlAccessorType(XmlAccessType.NONE): annotated fields and annotated properties
    0 讨论(0)
  • 2020-12-07 07:08

    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.

    0 讨论(0)
提交回复
热议问题