What's the difference between JAXB annotations put on getter versus setters versus members?

前端 未结 2 1617
闹比i
闹比i 2021-02-07 02:01

Title says it all.

I would like to know what is the principial difference between putting JAXB annotation (like @XmlElement) on field / getter / setter. It

相关标签:
2条回答
  • 2021-02-07 02:31

    By default JAXB impls will treat properties (get/set pairs), public fields (instance variables), and annotated non-public fields as mapped. If you just annotate a field you will get a duplicate mapped property exception.

    If you want to annotate the field you should specify @XmlAccessorType(XmlAccessType.FIELD) on the class.

    For More Information

    • http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html
    0 讨论(0)
  • 2021-02-07 02:31

    I have found no differences in marking JAXB annotations on setter methods and getter methods. I tested both marshalling and unmarshalling, and they both worked fine. But you should only annotate one of them; either the getter method or the setter method; you cannot annotate both, else you will get a runtime exception like the following.

    com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
    at com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException$Builder.check(IllegalAnnotationsException.java:91)
    at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:445)
    at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:277)
    at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:124)
    at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(JAXBContextImpl.java:1123)
    at com.sun.xml.internal.bind.v2.ContextFactory.createContext(ContextFactory.java:147)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:247)
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:234)
    at javax.xml.bind.ContextFinder.find(ContextFinder.java:462)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:641)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:584)
    
    0 讨论(0)
提交回复
热议问题