2016-12-20 119 views
1

我有下面的代碼將xml解組成Java對象。我想看看是否可以通過使用Java泛型而不是使用Object類型作爲返回值來增強此代碼。解析Java的泛型JAXB對象

protected static <T> Object unmarshall(String xml, Class<T> clazz) 
     throws JAXBException { 
    JAXBContext jc = JAXBContext.newInstance(clazz); 
    Unmarshaller unmarshaller = jc.createUnmarshaller(); 
    Object obj = unmarshaller.unmarshal(new StringReader(xml)); 
    return obj; 
} 

有什麼建議。

回答

3

是的,你可以提高你的代碼一點點:

protected static <T> T unmarshall(String xml, Class<T> clazz) 
     throws JAXBException { 
    JAXBContext jc = JAXBContext.newInstance(clazz); 
    Unmarshaller unmarshaller = jc.createUnmarshaller(); 
    T obj = clazz.cast(unmarshaller.unmarshal(new StringReader(xml))); 
    return obj; 
} 
+0

感謝您的輸入! – Vel

+1

SuppressWarnings是一種隱藏程序員錯誤的快速和骯髒的解決方法。爲什麼不使用[typesafe版本](http://docs.oracle.com/javase/8/docs/api/javax/xml/bind/Unmarshaller.html#unmarshal-javax.xml.transform.Source-java.lang .Class-)代替:'T obj = unmarshaller.unmarshal(new StreamSource(new StringReader(xml)),clazz).getValue();' – VGR

+0

@VGR將類綁定到任何rootelement(忽略實際的名稱根元素)。即使在上下文中有更好的匹配。更好的方法是使用clazz.isInstance()和clazz.cast()來避免未經檢查的轉換,並提供預期的結果。編輯: –

1

如果你不需要想重用的JAXBContext,無需創建它。有一個方便的方法(幾乎)有你想要的方法簽名。它拋出一個RuntimeException(許多人喜歡)。

protected static <T> T unmarshall(String xml, Class<T> clazz) { 
    return JAXB.unmarshal(new StringReader(xml), clazz); 
} 

但是,imo,只是直接使用該方法沒有包裝。

重複使用JAXBContext可以使長期運行速度更快(un)。另一個改進是clazz.cast(),以避免令人討厭的未經檢查的投射

private static final ConcurrentMap<Class<?>, JAXBContext> CONTEXT = new ConcurrentHashMap<>(); 

protected static <T> T unmarshall(String xml, Class<T> clazz) 
     throws JAXBException { 
    JAXBContext context = CONTEXT.get(clazz); 
    if (context == null){ 
     context = JAXBContext.newInstance(clazz); 
     CONTEXT.putIfAbsent(clazz, context); 
    } 

    Unmarshaller unmarshaller = context.createUnmarshaller(); 
    Object obj = unmarshaller.unmarshal(new StringReader(xml)); 
    if (clazz.isInstance(obj)){ 
     return clazz.cast(obj); 
    } 
    throw new IllegalArgumentException("XML does not represent an instance of type:" + clazz.getName()); 
}