如何使对象.class类型泛型



我想创建一个实用程序方法,该方法将两个对象作为参数并从中编组XML。 如果我对 from 参数使用实际的对象类型,下面的代码有效,但是如何使它成为泛型?下面的不会编译,因为它无法将 from 对象解析为类型。有什么想法吗?

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

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

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

这在 javadoc Ojbect#getClass()中有解释。

返回此对象的运行时类。

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

最新更新