title: How can I dynamically create an instance of a class in java?
body: <p>I would like to create an object dynamically.</p>
  
  <p>I have the following structure:
  1 abstract class and several classes that inherit from the abstract class</p>
  
  <pre class="lang-java prettyprint-override"><code>abstract public class A {..}
  
  
  public class B extends A{..}
  public class C extends A{..}
  </code></pre>
  
  <p>I have a config file where i want to add a class name, to have the ability to control which class it should be used.</p>
  
  <pre><code># config class name
   classname = B
  </code></pre>
  
  <p>I tried the following, but here I have the problem that I have to cast the result
  and I do not know how I can do it dynamically at this point</p>
  
  <pre class="lang-java prettyprint-override"><code>public class TestClass {
  
    public A instB;
  
    public void getInstance(){
      this.instB = Class.forName("B") /*here i put later the config value classname*/
      .getConstructor(String.class)
      .newInstance(new Object[]{"test"});   // &lt;--- How to cast this dynamicly to a class in the config?
    }
  }
  </code></pre>
  
  <p>How can I dynamically create an instance of a class?</p>