title: JAVA reflection cast object to class given by name of a specific supertype
body: <p>For example I've superclass Animal in a master package and sub-classes Dog and Cat in specific jars. All classes are JPA entities.</p>
  
  <pre><code>public class Animal {
  }
  
  public class Dog extends Animal{
  }
  
  public class Cat extends Animal{
  }
  </code></pre>
  
  <p>I've a method that get Animal as parameter.</p>
  
  <pre><code>public createAnimal(Animal a){
     this.em.persist(a);
  }
  </code></pre>
  
  <p>Now I want to pass an object of type Dog or Cat to that method</p>
  
  <pre><code>Animal a = ... //read from somewhere...
  String myClass = "my.package.Dog";// at runtime
  Class specific = Class.forName(myClass);
  createAnimal(specific.cast(a));
  </code></pre>
  
  <p>I can't import Dog and Cat in my master package because it must be generic (I use it in other EARs). </p>
  
  <p>So, how can I cast to specific classes defined by name and let the system know that is a subtype of Animal?</p>
  
  <p>I need something like this:</p>
  
  <pre><code>Class&lt;Animal&gt; specific = Class.forName(myClass);
  </code></pre>
  
  <p>but I miss something.</p>