@XmlSeeAlso不适用于同一根节点



我正在尝试用@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]

为什么您的类ChildAB和ChildCD是静态的?此外,ChildAB和ChildCD应实施/扩展您的Parent类。

相关内容

  • 没有找到相关文章

最新更新