title: Cast Object to Generic Type for returning
body: <p>Is there a way to cast an object to return value of a method?
  I tried this way but it gave a compile time exception in "instanceof" part:</p>
  
  <pre><code>public static &lt;T&gt; T convertInstanceOfObject(Object o) {
      if (o instanceof T) {
          return (T) o;
      } else {
          return null;
      }
  }
  </code></pre>
  
  <p>I also tried this one but it gave a runtime exception, ClassCastException:</p>
  
  <pre><code>public static &lt;T&gt; T convertInstanceOfObject(Object o) {
      try {
          T rv = (T)o;
          return rv;
      } catch(java.lang.ClassCastException e) {
          return null;
      }
  }
  </code></pre>
  
  <p>Is there a possible way of doing this easily:</p>
  
  <pre><code>String s = convertInstanceOfObject("string");
  System.out.println(s); // should print "string"
  Integer i = convertInstanceOfObject(4);
  System.out.println(i); // should print "4"
  String k = convertInstanceOfObject(345435.34);
  System.out.println(k); // should print "null"
  </code></pre>
  
  <p>EDIT: I wrote a working copy of the correct answer:</p>
  
  <pre><code>public static &lt;T&gt; T convertInstanceOfObject(Object o, Class&lt;T&gt; clazz) {
      try {
          return clazz.cast(o);
      } catch(ClassCastException e) {
          return null;
      }
  }
  
  public static void main(String args[]) {
      String s = convertInstanceOfObject("string", String.class);
      System.out.println(s);
      Integer i = convertInstanceOfObject(4, Integer.class);
      System.out.println(i);
      String k = convertInstanceOfObject(345435.34, String.class);
      System.out.println(k);
  }
  </code></pre>