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 |
package com.javabycode.object; public interface HelloWorld { public String sayHelloWorld(); } |
The class HelloWorldImpl implements the method sayHelloWorld().
1 2 3 4 5 6 7 8 9 10 |
package com.javabycode.object; public class HelloWorldImpl implements HelloWorld{ public HelloWorldImpl() { } public String sayHelloWorld() { 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package com.javabycode.object; public class ClassDemo { public static void main(String[] args) { HelloWorldImpl hello; hello = createInstanceByClassName("com.javabycode.object.HelloWorldImpl"); System.out.println("Say Hello: " + hello.sayHelloWorld()); } public static HelloWorldImpl createInstanceByClassName(String whichClass) { try { Class clazz = Class.forName(whichClass); return (HelloWorldImpl) clazz.newInstance(); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e){ e.printStackTrace(); } return null; } } |
Here is the result when you run the class ClassDemo
1 |
Say Hello: Hello Every Body |
Please leave comment if you like or have any question.
Happy learning!