简体   繁体   English

我如何使代码块通用?

[英]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 : 第3行:

"Item" and Item.class are the hardcoded value. “ Item”和Item.class是硬编码的值。

if i have to marshall Order xml, then i have to write a new method or if-else condition to achieve. 如果我必须编组Order xml,那么我必须编写一个新方法或if-else条件来实现。

How can i make this method more generic so that i can use this method for multiple class.. 我怎样才能使这种方法更通用,以便我可以将此方法用于多个类。

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);

This would do it: 这样做:

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

I hope it helps! 希望对您有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM