问题
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