I have a class that I wish to populate with content from an XML file using JAXB. My XML file looks similar to this:
<root>
<mylist>
<item id="1">First Item</item>
<item id="2">Second Item</item>
</mylist>
</root>
My JAXB annotated classes look like:
@XmlRootElement
class MyParentClass {
// I always populate this with a TreeSet
private Set<MyFieldItem> items;
public void setItems(Set<MyFieldItem> items) {
this.items = items;
}
@XmlElementWrapper("mylist") @XmlElement("item")
public Set<MyFieldItem> getItems() {
return items;
}
}
class MyFieldItem implements Comparable<MyFieldItem> {
private Integer id;
private String value;
public void setId(Integer id) {
this.id = id;
}
@XmlAttribute
public Integer getId() {
return id;
}
public void setValue(String value) {
this.value = value;
}
@XmlValue
public String getValue() {
return value;
}
public int compareTo(MyfieldItem o) {
return this.id.compareTo(o.getId());
}
}
I find that this arrangement serialises my objects to XML correctly, but when I try to convert it back the TreeSet I use becomes a HashSet.
In theory my collection could be fixed to a TreeSet (which does fix the problem), but I'd rather configure JAXB correctly and defer that logic elsewhere. How do I tell JAXB to build a TreeSet instead?