How to dynamically create an object in Java from a class name given as string format
To create an object dynamically from the class name, you need to use a reflection.
If the fully-qualified name of a class is available, it is possible to get the corresponding Class using the static method Class.forName(). However, This cannot be used for primitive types.
Having the Class type, you need to use the newInstance() function. It uses the constructor represented by the class object to create and initialize a new instance of the constructor’s declaring class, with the specified initialization parameters.
String className = "MyTestClass"; String fullPathOfTheClass = "full.path.to.the.class." + className; Class cls = Class.forName(fullPathOfTheClass); MyTestClass myTestObject = (MyTestClass) cls.newInstance(); // now I can use the object methods as usual myTestObject.myFunction();
In order to dynamically create an object in Java from an inner class name, you should use the $ sign.
String className = "MyTestClass"; String innerClassName = "MyInnerTestClass"; String fullPathOfTheClass = "full.path.to.the.class." + className + "$" + innerClassName;
Inner class names are delimited with $, not with a period. This means that the class name is: MyTestClass$MyInnerTestClass.
The $ syntax is valid for class loading only. Use periods to access instances of the class in source
private MyTestClass.MyInnerTestClass myInnerObject;