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 >

A powerful feature of JavaSW is to be able to instantiate a class using the String name of the class. If Java 'knows' about the class (ie, it exists somewhere in the classpathW classes and jars) within the context of your application, you can obtain a reference to this Class and instantiate an object of this class via the Class class. Normally in Java you would need to have an 'import' at the top of your .java file at compile-time, but if you use this technique, this import is not needed because the class to be used is determined at runtime based on the String name of the class.

A common use of this technique is to specify a class String name as an init param of a servletW or as an entry in a properties file. In the case of the properties file, this allows someone to specify a particular class to be used in the application by specifying the class name as a String in the properties file. This allows you to change the particular classes being used in an application without requiring any code changes, which is extremely powerful!

This example features an interface called SayHelloInterface, a HelloEnglish class that implements SayHelloInterface, a HelloSwedish class that implements SayHelloInterface, and a ClazzTest class that contains our main method.

'testing' project in Eclipse

The trivial SayHelloInterface interface is shown below. It declares a single method, sayHello().

SayHelloInterface.java

package test;

public interface SayHelloInterface {
	public String sayHello();
}

The HelloEnglish class implements the sayHello() method by returning "Hello".

HelloEnglish.java

package test;

public class HelloEnglish implements SayHelloInterface {
	public HelloEnglish() {
	}

	public String sayHello() {
		return "Hello";
	}
}

The HelloSwedish class implements the sayHello() method by returning "Hej".

HelloSwedish.java

package test;

public class HelloSwedish implements SayHelloInterface {
	public HelloSwedish() {
	}

	public String sayHello() {
		return "Hej";
	}
}

(Continued on page 2)

Page:    1 2 >