@XmlElementWrapper with shared list and inheritance

I would like to do the following:

public abstract class SomeItems<E> { protected List<E> items; public void setItems(List<E> items) { this.items = items; } ....do other stuff with items.... } @XmlRootElement(name = "foos") public class Foos extends SomeItems<Foo> { @XmlElementWrapper(name="items") @XmlElement(name="foo") public List<Foo> getItems() { return this.items; } } @XmlRootElement(name = "bars") public class Bars extends SomeItems<Bar> { @XmlElementWrapper(name="items") @XmlElement(name="bar") public List<Bar> getItems() { return this.items; } } 

But this leads to the following XML:

 <foos> </foos> 

What I'm trying to get is:

 <bars> <items> <bar>x</bar> <bar>y</bar> </items> </bars> <foos> <items> <foo>x</foo> <foo>y</foo> </items> </foos> 

But the only way to get this XML is to do the following:

 public abstract class SomeItems<E> { protected List<E> items; public void setItems(List<E> items) { this.items = items; } @XmlElementWrapper(name="items") @XmlElements({ @XmlElement(name="foo", type=Foo.class), @XmlElement(name="bar", type= Bar.class) }) public List<E> getItems() { return this.items; } } @XmlRootElement(name = "foos") public class Foos extends SomeItems<Foo> { } @XmlRootElement(name = "bars") public class Bars extends SomeItems<Bar> { } 

But I do not want the abstract class to have any knowledge of which classes extend it.

+1
source share

Source: https://habr.com/ru/post/1488638/


All Articles