1

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.

tanya
  • 508
  • 4
  • 12
  • you are missing a lot of annotations, don't you have an XSD? the easiest way is starting from the XSD and using mvn jaxb:generate to create your java classes skeleton – ilcavero Mar 28 '12 at 16:09
  • I tried something similar to the last answer in this posting: [link](http://stackoverflow.com/questions/4144296/marshalling-a-list-of-objects-with-jaxb) using "@XmlElementRef()" instead of "@XmlElements" in the abstract class, but get this exception: "Exception Description: Invalid XmlElementRef on property items on class SomeItems. Referenced Element not declared." Bar and Foo have "@XmlRootElements" defined on their classes too. – tanya Mar 28 '12 at 17:07
  • And that last exception seems similar to [this bug](http://www.google.com/url?sa=t&rct=j&q=exception%20description%3A%20invalid%20xmlelementref%20on%20property%20items%20on%20class%20%20%22referenced%20element%20not%20declared.%22&source=web&cd=1&ved=0CCQQFjAA&url=https%3A%2F%2Fbugs.eclipse.org%2Fbugs%2Fshow_bug.cgi%3Fid%3D327811&ei=NkZzT5iPEonfgQf824BM&usg=AFQjCNGiGQ5vwi_eIGYSdJ1VZTQk3prMyg&cad=rja), but the fix was for inheritance, not generics. – tanya Mar 28 '12 at 17:12

0 Answers0