Search code examples
javaxstream

How can i make block of code generic?


public Item marshallItem(String xml) {
    // TODO Auto-generated method stub
    XStream xstream = new XStream();

    xstream.alias("Item", Item.class);

    return (Item) xstream.fromXML(xml);
}

Line no 3 :

"Item" and Item.class are the hardcoded value.

if i have to marshall Order xml, then i have to write a new method or if-else condition to achieve.

How can i make this method more generic so that i can use this method for multiple class..


Solution

  • Something like this will do the thing:

    public <T> T marshallItem(String xml, Class<T> clazz) {
        XStream xstream = new XStream();
        xstream.alias(clazz.getSimpleName(), clazz);
        return (T) xstream.fromXML(xml);
    }
    

    Calling this method:

    Item info = marshallItem("yourXml", Item.class);