繁体   English   中英

用简单的示例无法使JAXB处理接口

[英]Can't get JAXB to handle interfaces with simple example

我正在尝试非官方JAXB指南-映射接口— Pr​​oject 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);

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

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

@XmlSeeAlso注释应用于Zoo类也应该可以。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM