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 seems to me that (in simple cases) it does not matter.
E.g. lets take this
class A { private String a; public String getA() { return a; } public void setA(String a) { this.a = a; } }
now it seems to me that it does not matter if I put @XmlElement
on member field or on getter / setter. It just marshalls ok. Are there any usecases when I need to make difference and when it does matter?
When I go to unmarshall this (xml back to A) what JAXB does specifically?
I am using JAXB MOXy implementation
Thanks
Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Given this, getters and setters are also known as accessors and mutators, respectively.
The getter and setter method gives you centralized control of how a certain field is initialized and provided to the client, which makes it much easier to verify and debug. To see which thread is accessing and what values are going out, you can easily place breakpoints or a print statement.
Using getters and setters, is always, in my opinion good practice. One thing you should avoid is to have external entities mess with the internal structure of your class at will. Typical example, consider having a dateOfBirth parameter.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With