1

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?

TheStiff
  • 365
  • 2
  • 10

4 Answers4

1

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();
RamonBoza
  • 8,898
  • 6
  • 36
  • 48
1
Class.forName(classNameReceivedAsParameter).newInstance();

You will need to concatenate the package name to the parameter to obtain the full class name. And, obviously, this will only work for classes which have a no-arg constructor.

Gabriel Negut
  • 13,860
  • 4
  • 38
  • 45
0

You can use the forName function of class. The solution is described here : What is the difference between "Class.forName()" and "Class.forName().newInstance()"?

Community
  • 1
  • 1
Julien
  • 2,544
  • 1
  • 20
  • 25
0

As said you can use reflection API:

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

But if you have arguments in the constructor you can use the get Constructor method to get the constructor with the right arguments:

Class.forName(yourClassPathPackage).getConstructor(String.class).newInstance("MyClass");
Steven
  • 307
  • 2
  • 13