title: Cast to generic subclass in Java
body: <p>I want to write universal function, which can make an object of any type by name and return it as its own type, not as Object type. </p>
  
  <pre class="lang-java prettyprint-override"><code>import java.lang.reflect.Constructor;
  public class Test{
      static &lt;T extends Object&gt; T makeObject(String className) {
          try {
              Class&lt;?&gt; c = Class.forName(className);
              Constructor&lt;?&gt; constructor = c.getConstructor();
              Object object = constructor.newInstance();
              return (T)c.cast(object);
          } catch (Exception e) {
              e.printStackTrace();
          }
          return null;
      }
      public static void main(String[] args) {
           //without casting
           String obj = makeObject("java.lang.String");
           System.out.println(obj.getClass());
      }
  }
  </code></pre>
  
  <p>It works fine, but I get the warning</p>
  
  <pre><code>Type safety: Unchecked cast from capture#4-of ? to T
  </code></pre>
  
  <p>What to do to fix the problem without adding <code>@SuppressWarnings("unchecked")</code>?</p>