使用简单示例

时间:2016-02-03 18:35:12

标签: java xml jaxb2

我正在尝试Unofficial JAXB Guide - Mapping interfaces — Project Kenai第3.2.1节中显示的JAXB接口的简单示例,但它不适合我。我在最新的JDK 1.8_70中没有使用任何特殊的库。完整代码:

@XmlRootElement
class Zoo {
  @XmlAnyElement
  public List<Animal> animals;
}

interface Animal {
  void sleep();
  void eat();
  ...
}

@XmlRootElement
class Dog implements Animal { ... }

@XmlRootElement
class Lion implements Animal { ... }

对此有何帮助?我得到的错误是:

[com.sun.istack.internal.SAXException2: class testjaxb.Cat nor any of its super class is known to this context.
javax.xml.bind.JAXBException: class testjaxb.Cat nor any of its super class is known to this context.]

编辑:发布JAXBContext.newInstance代码:

Zoo zoo = new Zoo();
zoo.animals = new ArrayList<Animal>();
zoo.animals.add( new Cat() );
zoo.animals.add( new Dog() );
zoo.animals.add( new Dog() );

JAXBContext ctx = JAXBContext.newInstance(Zoo.class);
Marshaller marshaller = ctx.createMarshaller();
marshaller.marshal(zoo, System.out);

1 个答案:

答案 0 :(得分:4)

尝试在您提供给JAXBContext.newInstance()的列表中指定其他类。

JAXBContext ctx = JAXBContext.newInstance(Zoo.class, Cat.class, Dog.class);

@XmlSeeAlso注释应用于Zoo课程也应该有效。

@XmlRootElement
@XmlSeeAlso({Cat.class, Dog.class})
class Zoo {
    ...
}