我尝试使用@XmlSeeAlso
注释实现继承。当为子类使用不同的根节点名称时,一切都按预期工作。但是使用相同的根名称,Unmarshaller总是从XmlSeeAlso列表中选择最后一个类,尽管内容很多。改变根名称是不可能的。有什么方法可以让Unmarshaller通过内容正确选择类?
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 + "]";
}
}
}
输出:
ChildCD[null; null]
ChildCD[CCC; DDD]
答案 0 :(得分:0)
为什么你的班级ChildAB和ChildCD是静态的? ChildAB和ChildCD也应该实现/扩展您的Parent类。