2014-04-29 199 views
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...事件失敗。

回答

0

我花了幾個小時詛咒Jaxb,終於找到解決我的問題的方法。缺少的東西是參數name@XmlRootElement(name = "child")的註釋中。這就是我所需要的,一切正常。

希望有人會覺得這有幫助,並節省他的時間。