简体   繁体   中英

How to Make Object.class Type Generic

I would like to create a utility method that takes two Objects as parameters and marshalls a XML from them. The below code works if I use the actual Object type for the from parameter, but how do I make this generic? The below wont compile since it can't resolve the from Object to a type. Any ideas?

 public static String getXML(Object from){
    StringWriter xml = new StringWriter();
    try {
      JAXBContext.newInstance(from.class).createMarshaller().marshal(from, xml);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return xml.toString();
  }

You can get the Class instance of an object like so

JAXBContext.newInstance(from.getClass()) //...

This is explained in the Ojbect#getClass() javadoc.

Returns the runtime class of this Object.

Note that there aren't any generics directly involved in this code snippet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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