I have the below code to unmarshall xml into Java objects. I would like to see if this code can be enhanced by using Java Generics instead of using Object type as return value.
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;
}
Any suggestions.
Yes, you can enhance your code a little bit:
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With