I have some data in an XML-file which i want to unmarshal with JAXB into MyHashMap. MyObject has an String name, which is the key in my HashMap.
To prevent writing the key/name information twice into my XML-File (once as the name of MyObject and once as the key of MyHashMap), so i added setter and getter for an ArrayList, which add/read the data into/out of MyHashMap.
@XmlRootElement
public class MyHashMap extends HashMap<String, MyObject> implements Serializable {
public MyHashMap() {
super();
}
@XmlElement(name = "MyObject")
public void setMyObjectsArrayList(ArrayList<MyObject> MyObjectList) {
for (MyObject myObject : MyObjectList) {
this.put(myObject.getName(), myObject);
}
}
public ArrayList<MyObject> getMyObjectsArrayList() {
if (this.isEmpty()) { // Added this to get my setter called
return null;
}
ArrayList<MyObject> MyObjectList = new ArrayList<MyObject>();
MyObjectList.addAll(this.values());
return MyObjectList;
}
}
It worked fine in Java 7 (according to the andswer of this because of a bug ), but doesnt in Java 8. In Java 8 JAXB gets the ListObject and adds the Elemts instead of using the setter.
So i added a "return null" if the list is empty. Apparently JAXB then sets an empty list and adds the Elements afterwards which obviously does not work with my code. Is there a possibility to tell JAXB to add the Elements to the list and call the setter only then?