As said in Oracle Documentation you can do it in the following way:
Class<?> clazz = Class.forName(className);
Constructor<?> ctor = clazz.getConstructor(String.class);
Object object = ctor.newInstance(new Object[] { ctorArgument });
Let me to provide a very simple example of such using:
Suppose we have that Main
class and the class we need to instanciate are in the same package. Then we can act as follows:
The class we need to instanciate:
public class MyClass {
public int myInt;
public MyClass(Integer myInt){
this.myInt = myInt;
}
}
main
method:
public static void main(String[] args) throws Exception {
//Class name must contain full-package path
// e.g. "full.pack.age.classname"
String className = Main.class.getPackage().getName() + ".MyClass";
Class<?> clazz = Class.forName(className);
//Class.getConstructor(Class<?> ... parameters) gives you a suitable constructor
//depends on the argument types you're going to pass to them.
Constructor<?> ctor = clazz.getConstructor(Integer.class);
//Object creation and constructor call
Object object = ctor.newInstance(new Object[] { 1 }); //1 is just myInt value passes to a contructor being invoked.
System.out.println(((MyClass) object).myInt); //Prints 1
}