title: How to perform a checked cast?
body: <p>I am new to Generics and am having an issue.</p>
  
  <p>Consider the following code:</p>
  
  <pre><code>public class A {}
  public class B extends A {}
  
  public &lt;T extends A&gt; T getB()
  {
      A test = new B();
      Class&lt;B&gt; clazz = B.class;
      if (clazz.isInstance(test))
      {
          return (T)test;
      }
      return null;
  }
  </code></pre>
  
  <p>This generates an Unchecked cast warning.  on the <code>return (T)test;</code> line.
  but clearly I am checking the type with the <code>if (clazz.isInstance(test))</code> line.</p>
  
  <p>Is there a way to do a "checked cast"?</p>
  
  <p>I'm not looking to just suppress the warning but actually implement a checked cast.  Unfortunately I can't find information on how to perform a checked cast.</p>