users@jaxb.java.net

JAXB inheritance conflict - Re-annotatig on sub-classes

From: Pedro Andrade Torres <shirkit_at_gmail.com>
Date: Sat, 28 Jul 2012 22:07:30 -0300

I currently have this enviorment on my project:

public abstract class Foo {

   private List<Thing> things;

   public List<Thing> getThings() { return this.things; }
}

public abstract class Bar extends Foo {


   @XmlElements({_at_XmlElement(name = "first", type = First.class)})

   public List<Thing> getThings() { return super.getThings(); }

}

public class Bobar extends Bar {

   @XmlElements({_at_XmlElement(name = "second", type = Second.class)})

   public List<Thing> getThings() { return super.getThings(); }

}

For the following XML document

<bobar>
   <first>blablabla</first>

   <second>blublublu</second>
</bobar>

When I do

context = JAXBContext.newInstance("the.package.structure");

unmarshaller = context.createUnmarshaller();
Bar object = (bar) unmarshaller.unmarshal("path-to-xml-document");

The object bar only has one element in the collection, not 2. The
Firstelement is completly lost, when I try to do
object.getThings(), it's size is 1 and the only object inside the
colleciotn is an instance of Second. Can someone help me how can I achieve
to get both objects in the collection? And if that's not possible, how can
I achieve something similar to this?

The reason I'm doing this is that (in mt project logic) every Bobar's
things collection has a First in it's collection, but not every Bar has a
Second in it's collection, and Foo is a generic class.
Edit:

When I change the order in my XML document, the output is different.

<bobar>
   <second>blablabla</second>

   <first>blublublu</first>
</bobar>

In this scenario, I get only an instance of First in the collection, and
Second is lost. And changing more the scenario, I get interesting results:

public abstract class Foo {

   private List<Thing> things;

   public List<Thing> getThings() { return this.things; }
}

public abstract class Bar extends Foo {


   @XmlElements({_at_XmlElement(name = "first", type = First.class),
@XmlElement(name = "third, type = Third.class)})

   public List<Thing> getThings() { return super.getThings(); }

}

public class Bobar extends Bar {

   @XmlElements({_at_XmlElement(name = "second", type = Second.class)})

   public List<Thing> getThings() { return super.getThings(); }

}

If I do

<bobar>
   <third>bliblibli</third>

   <second>blablabla</second>

   <first>blublublu</first>
</bobar>

In theory, I think this shouldn't be validated against the XML Schema
generated by that, as the order here is not correct. But besides that, in
such scenario, I get Second and First, the Third is lost.


------------------------
Atenciosamente,
Pedro Torres <http://lattes.cnpq.br/2854076896215610>
<shirkit_at_gmail.com>