title: Java generics
body: <p>I'd like to implement a method that takes an <code>Object</code> as argument, casts it to an arbitrary type, and if that fails returns <code>null</code>.  Here's what I have so far:</p>
  
  <pre><code>public static void main(String[] args) {
      MyClass a, b;
      a = Main.&lt;MyClass&gt;staticCast(new String("B"));
  }
  
  public static class MyClass {
  }
  
  public static &lt;T&gt; T staticCast(Object arg) {
      try {
          if (arg == null) return null;
          T result = (T) arg;
          return result;
      } catch (Throwable e) {
          return null;
      }
  }
  </code></pre>
  
  <p>Unfortunately the class cast exception is never thrown/caught in the body of the <code>staticCast()</code> function. It seems Java compiler generates the function <code>String staticCast(Object arg)</code> in which you have a line <code>String result = (String) arg;</code> even though I explicitly say that the template type should be <code>MyClass</code>.  Any help?  Thanks.</p>