[英]unmarshall to class with generic param
我正在嘗試使用庫JAXB將xml字符串反序列化為特定的類。
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正在嘗試初始化Base
接口,該操作失敗,但發生異常Unable to create an instance of sandbox.Base...
盡管將類名傳遞給JAXBContext.newInstance
函數,但Unable to create an instance of sandbox.Base...
事件。
我花了幾個小時罵Jaxb,終於找到了解決我問題的方法。 缺少的是@XmlRootElement(name = "child")
注釋中的參數name
。 這就是我所需要的,一切都很好。
希望有人會對此有所幫助並節省時間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.