java - 无法通过简单的示例让 JAXB 处理接口(interface)

标签 java xml jaxb2

我正在尝试 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/

相关文章:

xml - 使用Powershell在xml中获取属性的元素名称

xml - 合并 XML 文档

java - JAXB 生成错误的类

Spring 3、JAXB2、Java 6、NamespacePrefixMapper 问题

java - Gson 抛出 IOException

java - 在分配参数之前如何验证参数?

Java - 因内存不足错误而关闭

java - 寻找一种方法将 0xa5 和 0x9c 组合成 0xa59c

java - Apache POI、Excel 2007+ XML 和 OSGI

java - JAXB 2.x : How to override an XmlElement annotation from parent class - Mission Impossible?