title: Java Reflection: Creating class instance dynamically and assigning it to Parent object
body: <pre><code>String child = "C";
  Parent p = null;
  try {
      Class c1 = new Class.forName(child);
      Constructor co = c1.getConstructor();
      // p=co.newInstance(null); //This gives compilatoin error cannot
      // conver object to Parent
      // p=(c1.getClass())co.newInstance(null);//also gives cast errror
      p = (Parent) co.newInstance(null);// this works but it typecasts the
      // child to Parent
  } catch (Exception e) {
  }
  </code></pre>
  
  <p>What am i trying to do.</p>
  
  <p>I have multiple Child classes inherited from Parent. I am getting child class name as string input.</p>
  
  <p>I want to instantiate the object of Child class and assign it to Parent. I do not want to type cast Child to Parent. As later in the code i need to compare two Child classes. If I typecast it to Parent. I cannot differentiate between Child1 and Child2.</p>