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().

1

2

3

4

5

6

7

packagecom.javabycode.object;

publicinterfaceHelloWorld{

publicStringsayHelloWorld();

}

The class HelloWorldImpl implements the method sayHelloWorld().

1

2

3

4

5

6

7

8

9

10

packagecom.javabycode.object;

publicclassHelloWorldImplimplementsHelloWorld{

publicHelloWorldImpl(){

}

publicStringsayHelloWorld(){

return"Hello Every Body";

}

}

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.