jeudi 24 janvier 2019

JAVA reflection cast object to class given by name of a specific supertype

For example I've superclass Animal in a master package and sub-classes Dog and Cat in specific jars. All classes are JPA entities.

public class Animal {
}

public class Dog extends Animal{
}

public class Cat extends Animal{
}

I've a method that get Animal as parameter.

public createAnimal(Animal a){
   this.em.persist(a);
}

Now I want to pass an object of type Dog or Cat to that method

Animal a = ... //read from somewhere...
String myClass = "my.package.Dog";// at runtime
Class specific = Class.forName(myClass);
createAnimal(specific.cast(a));

I can't import Dog and Cat in my master package because it must be generic (I use it in other EARs).

So, how can I cast to specific classes defined by name and let the system know that is a subtype of Animal?

I need something like this:

Class<Animal> specific = Class.forName(myClass);

but I miss something.





Aucun commentaire:

Enregistrer un commentaire