生成された型がインターフェースであるリストであるフィールドの 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.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 {}
}