用简单的例子无法让JAXB处理接口 [英] Can't get JAXB to handle interfaces with simple example
问题描述
我正在尝试在非官方的JAXB指南 - 映射接口 - 项目Kenai ,第3.2.1节,它对我不起作用。我是最新的JDK 1.8_70并没有使用任何特殊的库。完整性代码:
I'm trying the simple example for JAXB Interfaces shown at Unofficial JAXB Guide - Mapping interfaces — Project Kenai, section 3.2.1 and it won't work for me. I'm in latest JDK 1.8_70 and not using any special libraries. Code for completeness sake:
@XmlRootElement
class Zoo {
@XmlAnyElement
public List<Animal> animals;
}
interface Animal {
void sleep();
void eat();
...
}
@XmlRootElement
class Dog implements Animal { ... }
@XmlRootElement
class Lion implements Animal { ... }
对此有何帮助?我得到的错误是:
Any help on this? The error I'm getting is:
[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代码:
Posted JAXBContext.newInstance code:
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()
。
Try specifying the other classes in the list you provide to JAXBContext.newInstance()
.
JAXBContext ctx = JAXBContext.newInstance(Zoo.class, Cat.class, Dog.class);
将 @XmlSeeAlso
注释应用于 Zoo
类也应该有效。
Applying the @XmlSeeAlso
annotation to your Zoo
class should also work.
@XmlRootElement
@XmlSeeAlso({Cat.class, Dog.class})
class Zoo {
...
}
这篇关于用简单的例子无法让JAXB处理接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!