Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics for unmarshall JAXB Object

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.

like image 316
Vel Avatar asked Dec 20 '16 17:12

Vel


1 Answers

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;
}
like image 169
Thomas Fritsch Avatar answered Sep 21 '22 12:09

Thomas Fritsch