JAXB marshalling declares parent class against actual run-time subclass

I use JAXB to marshal a class with an instance variable declared as a Foo class. At run time, this instance variable is set to an instance of a subclass of Foo, say FooBar. There are basic JAXB annotations for both the Foo and FooBar classes.

The XML output shows that the Foo instance is marshaled instead of the FooBar. Is there anything concrete I have to do in terms of annotations in order to tell JAXB how to properly marshal the runtime subclass instead of the declared superclass?

I tried an experiment in which I directly marshaled an instance variable foo of type Foo, which was set to an instance of FooBar at runtime. He correctly ordered the FooBar instance.

This is clearly different from marshaling a class containing an instance variable of type Foo, because the marshal is called in the containing class, and JAXB simply arranges the class fields (I use the @XmlAccessorType annotation (XmlAccessType.FIELD)).

My expectation was that JAXB could correctly check the type of runtime of an instance variable, but maybe that is not the case. Does this situation describe the use of the XmlAdapter implementation as described here?

JAXB inheritance not related to subclass of marshaled class

Thank,

Chris

+5
source share
1 answer

I will use these classes as an example:

@XmlRootElement
class Foo { public Bar bar; }
class Bar {}
class Baz extends Bar {}
class Quux extends Bar {}

Well, there seem to be two possible solutions:

JAXB ( ) .

JAXBContext.newInstance(Foo.class, Bar.class, Baz.class, Quux.class);

JAXB @XmlSeeAlso.

@XmlRootElement
@XmlSeeAlso({Baz.class, Quux.class})
class Foo { public Bar bar; }

Foo f = new Foo();
f.bar = new Baz();

m.marshal(f, System.err);

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<foo>
    <bar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="baz"/>
</foo>

, .

+7

All Articles