title: Java Reflection - Getting a Type from an object to instantiate a generic
body: <p>I've never really used reflection before and am attempting something I'm not sure is possible. Basically, I'm trying to write a method that takes an <code>Object</code> as a parameter, and then attempts to marshal that object regardless of its type. I can't figure out how to get the type to use when instantiating the generic <code>JAXBElement&lt;T&gt;</code> object. Is this possible? My attempt:</p>
  <pre><code>String marshalObject(Object obj) {
      Class c = obj.getClass();
      Type t = (Type) c;
      
      QName _QNAME = new QName(&quot;http://www.acme.com/ImportExport&quot;, c.getName());
      StringWriter sw = new StringWriter();
      try {
          ObjectFactory of = new ObjectFactory();
          JAXBElement&lt;?&gt; jaxElement = new JAXBElement&lt;t&gt;(_QNAME, c, null, obj);
          JAXBContext context = JAXBContext.newInstance( c );
          Marshaller m = context.createMarshaller();
          m.marshal( jaxElement, sw );
      } catch( JAXBException jbe ){
          System.out.println(&quot;Error marshalling object: &quot; + jbe.toString());
          return null;
      }
      
      return sw.toString();
  }
  </code></pre>