我在使用 JAXB 注释来处理某个字段时遇到问题,该字段是一个泛型类型为接口的列表。当我声明如下时:
@XmlAnyElement
private List<Animal> animals;
每件事都正常进行。但是当我添加包装元素时,例如:
@XmlElementWrapper
@XmlAnyElement
private List<Animal> animals;
我发现 Java 对象正确封送,但是当我解封封送创建的文档时,我的列表为空。我在下面发布了代码来演示这个问题。
我做错了什么,还是这是一个错误?我已经用版本 2.1.12 和 2.2-ea 尝试过,结果相同。
我正在研究使用此处的注释映射接口的示例: https://jaxb.dev.java.net/guide/Mapping_interfaces.htmlhttps://jaxb.dev.java.net/guide/Mapping_interfaces.html https://jaxb.dev.java.net/guide/Mapping_interfaces.html
@XmlRootElement
class Zoo {
@XmlElementWrapper
@XmlAnyElement(lax = true)
private List<Animal> animals;
public static void main(String[] args) throws Exception {
Zoo zoo = new Zoo();
zoo.animals = new ArrayList<Animal>();
zoo.animals.add(new Dog());
zoo.animals.add(new Cat());
JAXBContext jc = JAXBContext.newInstance(Zoo.class, Dog.class, Cat.class);
Marshaller marshaller = jc.createMarshaller();
ByteArrayOutputStream os = new ByteArrayOutputStream();
marshaller.marshal(zoo, os);
System.out.println(os.toString());
Unmarshaller unmarshaller = jc.createUnmarshaller();
Zoo unmarshalledZoo = (Zoo) unmarshaller.unmarshal(new ByteArrayInputStream(os.toByteArray()));
if (unmarshalledZoo.animals == null) {
System.out.println("animals was null");
} else if (unmarshalledZoo.animals.size() == 2) {
System.out.println("it worked");
} else {
System.out.println("failed!");
}
}
public interface Animal {}
@XmlRootElement
public static class Dog implements Animal {}
@XmlRootElement
public static class Cat implements Animal {}
}
应该使用
@XmlElementRefs({
@XmlElementRef(类型=Dog.class),
@XmlElementRef(type=Cat.class)})
私人名单动物;
或使用
仅限 @XmlAnyElement(lax = true),并将 Dog.class、Cat.class 添加到 JaxbContext
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)