0
我想反序列化具有庫JAXB的xml字符串到特定的類。unmarshall類與泛型參數
public class Sandbox {
public static void main(String[] args) throws JAXBException {
String xml = "<root><child><base-value>val1</base-value><baseimpl-value>val2</baseimpl-value></child></root>";
Sandbox.Do(xml, BaseImpl.class);
}
public static void Do(String xml, Class c) throws JAXBException{
JAXBContext jc = JAXBContext.newInstance(Parent.class, c);
Unmarshaller um = jc.createUnmarshaller();
Parent<BaseImpl> p = (Parent<BaseImpl>) um.unmarshal(new StringReader(xml));
System.out.println(p.child);
}
}
@XmlRootElement(name = "root")
class Parent<T extends Base> {
@XmlElement
T child;
}
abstract class Base {
@XmlElement(name = "base-value")
String BaseValue;
}
@XmlRootElement
class BaseImpl extends Base {
@XmlElement(name = "baseimpl-value")
String BaseImplValue;
@Override
public String toString(){
return super.BaseValue + ", " + this.BaseImplValue;
}
}
JAXB試圖initiliaze Base
接口,但類名被傳遞給JAXBContext.newInstance
功能與什麼異常Unable to create an instance of sandbox.Base...
事件失敗。