如何使Object.class类型Generic

时间:2013-09-24 16:58:30

标签: java jaxb

我想创建一个实用程序方法,它将两个对象作为参数并从中对其进行编组。如果我使用from参数的实际Object类型,下面的代码可以工作,但是如何使这个通用?下面不会编译,因为它无法将from Object解析为类型。有什么想法吗?

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

1 个答案:

答案 0 :(得分:1)

你可以获得像这样的对象的Class实例

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

Ojbect#getClass() javadoc中解释了这一点。

  

返回此Object的运行时类。

请注意,此代码段中没有直接涉及任何泛型。