Matt
Matt

Reputation: 1531

how to use @XmlElement in java

I'm trying to learn how to store objects as XML files in java, but I'm having a bit of a problem.

Most tutorials that I have found have said that I should use the @XmlElement annotation with set methods, however is there another way to use them, as my objects would be easier to make using just the constructors I have for them instead of a set for each field.

Upvotes: 1

Views: 1942

Answers (2)

bdoughan
bdoughan

Reputation: 149047

All public fields and properties (get/set method pairs) will be treated by default as if they were annotated with @XmlElement. You can add @XmlElement on the get or set method. You can also annotate the field (instance variable). If you do you should annotate your class with @XmlAccesorType(XmlAccessType.FIELD).

JAXB does not currently support annotating constructors. If you are dealing with immutable objects then the following may help:

Upvotes: 0

LaurentG
LaurentG

Reputation: 11797

The @XmlElement can also be used on the property. You will find more information in the javadoc.

The javadoc gives this example:

public class USPrice {
    @XmlElement(name="itemprice")
    public java.math.BigDecimal price;
}

Upvotes: 2

Related Questions