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.

For example:

String className = "MyTestClass";
String fullPathOfTheClass = "" + className;
Class cls = Class.forName(fullPathOfTheClass);
MyTestClass myTestObject = (MyTestClass) cls.newInstance();
// now I can use the object methods as usual

In order to dynamically create an object in Java from an inner class name, you should use the $ sign.
For Example:

String className = "MyTestClass";
String innerClassName = "MyInnerTestClass";
String fullPathOfTheClass = "" +
				className +
				"$" +

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
For example:

private MyTestClass.MyInnerTestClass myInnerObject;

For more information see:
1. Using Java Reflection
2. Retrieving Class Objects

  1. Anita Wang says:

    The whole purpose of doing
    Class cls = Class.forName(fullPathOfTheClass);
    is so that the class name is not used directly in later declaration.

    If could use:
    MyTestClass myTestObject = (MyTestClass) cls.newInstance();
    then why don’t I just directly use:
    MyTestClass myTestObject = new MyTestClass();

    You cannot use MyTestClass directly anywhere in this code for it to be really dynamic.

  2. cyus says:

    totally agree with anita…. the whole purpose of this exercise get defeated when you use…
    MyTestClass myTestObject = (MyTestClass) cls.newInstance();

Leave a Reply