如果你不需要想重用的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());
}
感謝您的輸入! – Vel
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
@VGR將類綁定到任何rootelement(忽略實際的名稱根元素)。即使在上下文中有更好的匹配。更好的方法是使用clazz.isInstance()和clazz.cast()來避免未經檢查的轉換,並提供預期的結果。編輯: –