@XmlElementWrapper with a generic List and inheritance

旧街凉风 提交于 2020-01-05 15:06:07

问题


I'd 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 results in the following XML:

<foos>
</foos>

What I'm trying to get, is this:

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

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

But, the only way I can get that 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 don't want the abstract class to have to have any knowledge of what classes are extending it.

来源:https://stackoverflow.com/questions/9911444/xmlelementwrapper-with-a-generic-list-and-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!