title: Casting a generic class. (cast) vs Class.cast()
body: <p>I have searched for my use case and found some interesting answers but they are not as suitable as i need. What would the appropriate way to do this:</p>
  
  <pre><code>@SuppressWarnings("unchecked")
  public &lt;T&gt; T newInstance(String name) throws ClassCastException, InstantiationException, IllegalAccessException, ClassNotFoundException {
      return (T) loadClass(name).newInstance();
  }
  </code></pre>
  
  <p>or a little different:</p>
  
  <pre><code>public &lt;T&gt; T newInstance(String name, Class&lt;T&gt; c) throws ClassCastException, InstantiationException, IllegalAccessException, ClassNotFoundException {
      return c.cast(loadClass(name).newInstance());
  }
  </code></pre>
  
  <p>I think that both methods do the same. From my point of view method 1 is better because of less parameters. Boths throw a <code>ClassCastException</code> which will be fine for me. Truly, the <code>@SuppressWarnings("unchecked")</code> annotation is not nice.</p>
  
  <p>Can someone tell me if there are any advantages for one method towards the other?</p>
  
  <p>Edit: <a href="https://stackoverflow.com/a/35860883/6032798">Jon Skeet's answer</a> is correct. The following snippet can provide additional clarification.</p>
  
  <pre><code>public class Test {
      public static void main(String[] args) {
          Object o = new Object();
          // Exception at c.cast(o)
          Test.&lt;String&gt;realCast(o, String.class);
      }
  
      private static &lt;T&gt; T realCast(Object o, Class&lt;T&gt; c) {
          return c.cast(o);
      }
  }
  </code></pre>
  
  <p>Using <code>realCast()</code> produces an Exception when <code>o</code> can't be cast to <code>c</code>. In comparison to that <code>fakeCast()</code> only gives a promise that the method's result is type of <code>T</code>.</p>