我正在尝试 Unofficial JAXB Guide - Mapping interfaces — Project Kenai 所示的 JAXB 接口(interface)的简单示例,第 3.2.1 节,它对我不起作用。我使用的是最新的 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 {
...
}
关于java - 无法通过简单的示例让 JAXB 处理接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35184975/