Create instance using class name in Java

You can create instance using class name if Java knows about the class (the class is stored somewhere of the classpath, ie) within the application context. Thus, you can get a reference to this Class and instantiate an its object via the Class class.

This technique is applied in many frameworks, web container, for example instantiating a servlet in tomcat and a service in serveral java web frameworks. This technique allows to change the particular classes being used in an application without requiring any code changes. It is extremely powerful.

I show you a code sample to demo this feature then you could debug or run it on your IDE to get more clearly.

This interface declares a single method, sayHelloWorld().

The class HelloWorldImpl implements the method sayHelloWorld().

The method createInstanceByClassName takes a class name as a parameter. A object of this class is obtained by the call to Class.forName with a parameter is the class name. If JVM can find the specified classes then object is instantiated successfully. If it can not find the specified classes then a ClassNotFoundException would be thrown.

Here is the result when you run the class ClassDemo

Please leave comment if you like or have any question.
Happy learning!

Leave a Comment


Please share it if you found this useful
Hide Buttons