title: Generics and Class.forName
body: <p>I would like to create an instance of a specified class using its name. My code is shown below.</p>
  
  <p>I get a compiler warning. Am I doing this the right way? Is it even possible to use the name of a class and get an instance of that type back, as I don't think there is any way of the compiler knowing what the type should be?</p>
  
  <pre><code>public static &lt;T&gt; T create(final String className) {
      try {
          final Class&lt;?&gt; clazz = Class.forName(className);
  
          //WARNING: Type safety: Unchecked cast from capture#2-of ? to T
          return (T) create(clazz); 
      }
      catch (ClassNotFoundException e) {
          e.printStackTrace();
      }
  }
  
  public static &lt;T&gt; T create(final Class&lt;T&gt; classToCreate) {
      final Constructor&lt;T&gt; constructor;
      try {
          constructor = classToCreate.getDeclaredConstructor();
          final T result = constructor.newInstance();
          return result;
      }
      catch (Exception e) {
          e.printStackTrace();
      }
  }
  </code></pre>
  
  <p>Thanks</p>