How To Load A Class Using Class.forName()

This example shows how to load a class using the Class.forName() method. All the classes in your application or dependent class files are loaded by appropriate class loader prior to using in the application. By default, class files are loaded by JVM when first time accessed by the applications. However, in certain situations you have to explicitly load the class files to make it available for your application.

Class.forName() is mostly used for loading the classes. If you would have used the JDBC APIs, there we have loaded the database driver class file using the Class.forName() method. When you pass the class name, note that it has to be passed as the fully qualified path.

Lets look at the below example to understand how the class loader loads the class. If the class is not found by the class loader, JVM will throw java.lang.ClassNotFoundException.

ClassForNameExample.java

package javabeat.net.core;

/**
 * Load class using Class.forName() Example
 *
 * @author Krishna
 *
 */
public class ClassForNameExample {

	public static void main(String[] args) {
		try {
			//Explicitly load class using forName()
			Class.forName("javabeat.net.core.One");
		} catch (ClassNotFoundException exception){
			exception.printStackTrace();
		}
		try {
			//Wrong way of specifying class name. It must be fully qualified path
			Class.forName("Two");
		} catch (ClassNotFoundException exception){
			exception.printStackTrace();
		}
		try {
			//Explicitly load class using forName()
			Class.forName("javabeat.net.core.Two");
		} catch (ClassNotFoundException exception){
			exception.printStackTrace();
		}

		//Create instance
		new Three();
	}
}

class One{
	static{
		System.out.println("Class One Loaded");
	}
}

class Two{
	static{
		System.out.println("Class Two Loaded");
	}
}

class Three{
	static{
		System.out.println("Class Three Loaded");
	}
}

Output…

java.lang.ClassNotFoundException: Two
	at java.net.URLClassLoader$1.run(Unknown Source)
	at java.net.URLClassLoader$1.run(Unknown Source)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.net.URLClassLoader.findClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at java.lang.Class.forName0(Native Method)
	at java.lang.Class.forName(Unknown Source)
	at javabeat.net.core.ClassForNameExample.main(ClassForNameExample.java:14)
Class One Loaded
Class Two Loaded
Class Three Loaded

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Pin It on Pinterest

Share This

Share this post with your friends!

Share This

Share this post with your friends!