Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 276
stewenson Avatar asked Mar 05 '14 11:03

stewenson


People also ask

What is the difference between setter and getter?

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.

What is the advantage of using getter and setter?

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.

Should you always use getters and setters?

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.


1 Answers

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
like image 167
bdoughan Avatar answered Oct 30 '22 05:10

bdoughan