我有以下代码将 xml 解码为 Java 对象。我想看看是否可以通过使用 Java 泛型而不是使用对象类型作为返回值来增强此代码。
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;
}
任何建议。
最佳答案
是的,您可以稍微增强您的代码:
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;
}
关于用于解码 JAXB 对象的 Java 泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41248307/