I appreciate that the answer to this could be ‘just be consistent’ but I’d like to understand whether there are advantages to adding annotations that apply to field/method to the field or the method. For example, are there any benefits of:
@XmlElement
private String str;
public String getString() {
return str;
}
over:
private String str;
@XmlElement
public String getString() {
return str;
}
Thanks.
It depends if there is logic in the get/set methods that you want to be executed during a marshal or unmarshal operation.
Example #1 – JPA Entities
Some JPA implementations use byte code manipulation to “weave” in code on the getter to perform lazy loading. If you are mapping this type of model to XML, then you will need to annotate the getter to ensure that the logic on the get methods is called.
Example #2 – Mismatched get/set Methods
In the answer below the user had non-compliant bean access methods. For that use case I recommended the use of field access.
Example #3 – Read-Only Properties
If your object model has properties with a getter but no setter, then field access is useful.
For More Information