How do I instantiate an object of a class via its String name?
Author: Deron Eriksson
Description: This Java tutorial shows how to use the forName and newInstance methods of Class to instantiate an object.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.1

Page: < 1 2

(Continued from page 1)

The ClazzTest class features a howdy method that takes a String class name as a parameter. The class object representing this class is obtained by the call to Class.forName with the class name as a parameter. Since the JVMW can find the classes specified in this example, no exception is thrown. If we tried calling Class.forName on a class that doesn't exist (like 'test.HelloFrench'), a ClassNotFoundException would be thrown.

The newInstance method is called on the class object that was obtained from the call to Class.forName, and this instantiates the object of the class specified in the forName call. The result is cast to the SayHelloInterface interface, and this is returned from the howdy method. The object's interface is returned to the main method and is called hello, and the sayHello method of hello is called. This is performed twice, first for the HelloEnglish class and secondly for the HelloSwedish class.

package test;

public class ClazzTest {

	public static void main(String[] args) {
		SayHelloInterface hello;
		hello = howdy("test.HelloEnglish");
		System.out.println("First Hello: " + hello.sayHello());
		hello = howdy("test.HelloSwedish");
		System.out.println("Second Hello: " + hello.sayHello());
	public static SayHelloInterface howdy(String whichClass) {
		try {
			Class clazz = Class.forName(whichClass);
			return (SayHelloInterface) clazz.newInstance();
		} catch (ClassNotFoundException e) {
		} catch (InstantiationException e) {
		} catch (IllegalAccessException e) {
		return null;

The execution of ClazzTest is shown below.

execution of ClazzTest console output

As you can see, the execution behaves exactly as expected. We specify the class names as Strings (which can be changed at runtime), and we use these Strings to obtain the classes which we use to instantiate objects of these classes. This technique is very powerful and leads to very dynamic applications.

Page: < 1 2