Can't get JAXB to handle interfaces with simple example

主宰稳场 提交于 2019-12-13 15:19:24

问题


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.]

EDIT: 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);

回答1:


Try specifying the other classes in the list you provide to JAXBContext.newInstance().

JAXBContext ctx = JAXBContext.newInstance(Zoo.class, Cat.class, Dog.class);

Applying the @XmlSeeAlso annotation to your Zoo class should also work.

@XmlRootElement
@XmlSeeAlso({Cat.class, Dog.class})
class Zoo {
    ...
}


来源:https://stackoverflow.com/questions/35184975/cant-get-jaxb-to-handle-interfaces-with-simple-example

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!