开发者

JAXB annotation for class hierarchy

Hey, I have 2 classes. When I'm trying to create an XML s开发者_C百科tructure from them, I only get the root element (A). Why? Am I using wrong annotations?

@XmlRootElement(name = "a")
@XmlAccessorType(XmlAccessType.FIELD)
public abstract class A{
    @XmlElement
    int a;

    protected A(){
    }
 }

@XmlAccessorType(XmlAccessType.FIELD)
public class B extends A{
    @XmlElement
    int b;

    protected B(){
    }
}    


You probably need to use @XmlSeeAlso annotation in your top class:

@XmlSeeAlso(B.class)
@XmlRootElement(name = "a")
@XmlAccessorType(XmlAccessType.FIELD)
public abstract class A{

I wrote 'probably', because it depends on how do you set up your JAXB context. Basically you need to make sure all the classes which are supposed to be serialized are known to JAXB. If your B class is not mentioned anywhere else (e.g. as a property type of one of classes which are already known to JAXB), then JAXB has no chance to know how to serialize instances of B. The intention of @XmlSeeAlso annotation is to make sure JAXB looks into these listed classes too.

UPDATE:

Alternatively you can provide the list of all the subclasses when creating the JAXBContext object using JAXBContext.newInstance(Class...), e.g.:

   JAXBContext.newInstance(A.class, B.class);

instead of

   JAXBContext.newInstance(A.class);

which you probably already do.

But my opinion this is a worse solution, because it makes you think of related classes every time you use JAXB in your code. In the top solution you set the relations once forever.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜