I'm trying to implement inheritance with @XmlSeeAlso
annotation. Everything works as expected when using different root node names for subclasses. But with the same root names Unmarshaller always choses the last class from the XmlSeeAlso list despite of the content. It's impossible to change root names. Is where any way to make Unmarshaller to chose class correctly by content?
import java.io.ByteArrayInputStream;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.transform.stream.StreamSource;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
public class Test {
public static void main(String[] args) {
Jaxb2Marshaller unmarshaller = new Jaxb2Marshaller();
unmarshaller.setClassesToBeBound(Parent.class);
System.out.println(unmarshaller.unmarshal(new StreamSource(
new ByteArrayInputStream("<value><a>AAA</a><b>BBB</b></value>"
.getBytes()))));
System.out.println(unmarshaller.unmarshal(new StreamSource(
new ByteArrayInputStream("<value><c>CCC</c><d>DDD</d></value>"
.getBytes()))));
}
@XmlSeeAlso({ ChildAB.class, ChildCD.class })
public static abstract class Parent {
}
@XmlRootElement(name = "value")
public static class ChildAB {
@XmlElement(name = "a")
private String a;
@XmlElement(name = "b")
private String b;
@Override
public String toString() {
return "ChildAB[" + a + "; " + b + "]";
}
}
@XmlRootElement(name = "value")
public static class ChildCD {
@XmlElement(name = "c")
private String c;
@XmlElement(name = "d")
private String d;
@Override
public String toString() {
return "ChildCD[" + c + "; " + d + "]";
}
}
}
Output:
ChildCD[null; null]
ChildCD[CCC; DDD]