jeudi 7 juin 2018

JAVA- Instanciation with variable

I'm wondering something about Java instanciation. Let'es take an example : I want to instanciate a class depending on some conditions like this :

Animal a = null;
if (string.equals("Dog")) a = new Dog();
else if (string.equals("Cat") a = new Cat();
etc...

I know it works but I would like to do something like this : Instead of doing a = new Dog(); I want to do something like this : a = new string(); (with string == "Dog")

Basically at runtime, string is replaced by "Dog". I know it is possible with API Reflection (with class.forName(string)).

But is it possible with "new" operator ?

Thanks





Aucun commentaire:

Enregistrer un commentaire