@XmlSeeAlso({ Dog.class, Cat.class })
public abstract class Animal {}
@XmlRootElement(name="dog")
public class Dog extends Animal {}
@XmlRootElement(name="cat")
public class Cat extends Animal {}
@WebService(name = "WebServiceDemo", serviceName = "WebServiceDemo")
@SOAPBinding(style = SOAPBinding.Style.DOCUMENT, use = SOAPBinding.Use.LITERAL,
parameterStyle = SOAPBinding.ParameterStyle.WRAPPED)
public class WebServiceDemo {
@WebMethod
public String service(@WebParam(name = "animal") Animal animal) {
System.out.println("animal service calling.....");
return animal;
}
}
现在当我从客户端使用Animal calss作为参数调用此服务方法时,我得到错误 -
引起:javax.xml.bind.UnmarshalException:无法创建Animal的实例 - 链接异常: [java.lang.InstantiationException] at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:616) at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:244) at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.createInstance(UnmarshallingContext.java:583) at com.sun.xml.bind.v2.runtime.unmarshaller.StructureLoader.startElement(StructureLoader.java:181) at com.sun.xml.bind.v2.runtime.unmarshaller.XsiTypeLoader.startElement(XsiTypeLoader.java:73) at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:455) at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(UnmarshallingContext.java:433) at com.sun.xml.bind.v2.runtime.unmarshaller.InterningXmlVisitor.startElement(InterningXmlVisitor.java:71) at com.sun.xml.bind.v2.runtime.unmarshaller.SAXConnector.startElement(SAXConnector.java:137) 在com.sun.xml.bind.unmarshaller.DOMScanner.visit(DOMScanner.java:240) 在com.sun.xml.bind.unmarshaller.DOMScanner.visit(DOMScanner.java:277) 在com.sun.xml.bind.unmarshaller.DOMScanner.visit(DOMScanner.java:246) 在com.sun.xml.bind.unmarshaller.DOMScanner.scan(DOMScanner.java:123) at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:314) at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:293) 在com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:244) 在org.jboss.ws.core.jaxws.JAXBDeserializer.deserialize(JAXBDeserializer.java:71)
答案 0 :(得分:2)
抽象类无法实例化,这是Java中的基本规则。来自javadocs:
抽象类是一个被声明为abstract的类 - 它可能也可能是 不包括抽象方法。抽象类无法实例化, 但它们可以被分类。
Jaxb内部会尝试将您的xml解组为java对象。但如果它无法创建Animal的对象,它将如何工作。因此它抛出异常。您需要为JaxB提供一个非抽象类才能工作。