2016-05-31 54 views
3

我有一些包使用POJO進行卸載。我想製作一個通用的方法,你可以通過什麼樣的課程,你會把它放到什麼地方。使用Java中的泛型解組XML使用泛型

例如:

pubic class Test<E> 
{ 
    E obj; 

    // Get all the tags/values from the XML 
    public void unmarshalXML(String xmlString) { 
     //SomeClass someClass; 
     JAXBContext jaxbContext; 
     Unmarshaller unmarshaller; 
     StringReader reader; 

     try { 
      jaxbContext = JAXBContext.newInstance(E.class); // This line doesn't work 
      unmarshaller = jaxbContext.createUnmarshaller(); 

      reader = new StringReader(xmlString); 
      obj = (E) unmarshaller.unmarshal(reader); 

     } catch(Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 

我上線的錯誤在上述代碼中指出:Illegal class literal for the type parameter E。當然,E將來自實際存在的POJO列表。

我該如何做到這一點?

回答

5

你不能做E.class,因爲編譯時會刪除泛型(轉換成Object類型,查看type erasure)。這是非法的,因爲通用類型數據在運行時不可訪問。

相反,你可以讓開發者可以通過構造函數傳遞類文字,將其存儲在外地,然後使用:

class Test<E> { 
    private Class<E> type; 

    public Test(Class<E> type) { 
     this.type = type; 
    } 

    public void unmarshall(String xmlString) { 
     //... 
     jaxbContext = JAXBContext.newInstance(type); 
    } 
} 

然後開發人員可以這樣做:

new Test<SomeType>(SomeType.class); 
+0

我'假設'reader = ...'下面的行是'type =(Class )unmarshaller.unmarshal(reader);'? – syy

+1

@Flow Nope。你仍然會使用'obj =(E)unmarshaller.unmarshal(reader)'。你不應該刪除'E obj'字段,因爲這是存儲解組數據的地方。這意味着你應該有2個字段:'type'和'obj'。 –

+0

哦,我明白了。非常感謝你的幫助! – syy