title: Casting a class using reflection in java
body: <p>I have the following classes.</p>
  
  <pre><code>abstract class A{}
  
  class B extends A{}
  
  class C extends A{}
  </code></pre>
  
  <p>I need to create an object like this</p>
  
  <pre><code>A a = new B();
  </code></pre>
  
  <p>I get the class name of the subclass at runtime. So, I need to use reflection to create an object.</p>
  
  <p>I have done this.</p>
  
  <pre><code>Class&lt;?&gt; klass = Class.forName(className);
  </code></pre>
  
  <p>Now I am not able to cast this class to the subclass.</p>
  
  <p>I want to achieve </p>
  
  <pre><code>A a = klass.newInstance(); // returns Object
  </code></pre>
  
  <p>I want the object to be casted into the subclass (either <code>B</code> or <code>C</code>, decided on runtime)</p>
  
  <p>How do I do this?</p>