Search code examples
javastringclassinstancecreation

How do i create an instance of a class based on a String without making multiple switches and if's?


hi I'm making a program that receives a String as input and based on that String i create an instance of a class.

The problem is that my program may have new classes in the future and i would like that when that happens i dont have to make much changes to my code, so i would like to avoid using chains of if's or switches.

for example if i receive "Class1" as input i want to create an instance of that class

but if in the future i want to be able to create an instance of "Class2" i dont want to have to change the previous code by adding a new if or a new case on a switch.

Is there anyway to do this?


Solution

  • You need the use of Reflection API.

    your string would have the full path of the package also

    String yourClassPathPackage = "com.your.class.path.YourClass";
    YourClass = (YourClass) Class.forName(yourClassPathPackage).newInstance();