title: Cast an object to class type passed as parameter
body: <p>I have a parent class and 2 child classes. I am trying to implement a function that takes the type of the child and which child as parameters.</p>
  
  <p>When I use <code>child.newInstance()</code>, I want to store it in a variable of the type that is passed and call a function from the second parameter.</p>
  
  <p>Below are the classes</p>
  
  <pre><code>public class Parent {
      public void test() {
          System.out.println("Test from parent");
      }
  }
  
  public class ChildA extends Parent {
      public void testChildA() {
          System.out.println("Test from child a");
      }
  }
  
  public class ChildB extends Parent {
      public void testChildB() {
          System.out.println("Test from child b");
      }
  }
  </code></pre>
  
  <p>and here is the method I'm trying to implement</p>
  
  <pre><code>public class Driver {
      Parent func(Class child, String whichChild) throws Exception {
          // whichChild: "ChildA" or "ChildB"
  
          Object obj = child.newInstance();
          // cast obj to type of child and call the method "test" and "test" + whichChild
      }
  }
  </code></pre>
  
  <p>Can it be done what I am trying to do? If yes, how can I cast this object to the type that is passed?</p>