Class.forName Example

In this post we will see a Class.forName Example and how it can be used to create dynamic objects.

Class.forName is commonly used while creating JDBC connections, but developers rarely know what it means.

It is a very unique way provided by Java to dynamically create objects without even knowing the class name at the time of coding (compile time)!

Lets see this is action for better understanding. We will build a quick Java application with 2 classes.

1) Example.java:

This is a simple class with a constructor which prints message “Example object created!!”

2) Main.java:

Contains the main method. We ask the user to enter a class name and create an object this type using Class.forName.

Here are the source files:

Example.java

package com.quicklyjava;

public class Example {

	public Example(){
		System.out.println("Example object created!!");
	}

}

Main.java

package com.quicklyjava;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			InputStreamReader in = new InputStreamReader(System.in);
			BufferedReader reader = new BufferedReader(in);
			System.out.println("Enter Class Name: ");
			String whatClass = reader.readLine();
			Class exampleClass = Class.forName(whatClass);
			Object ob = exampleClass.newInstance();
	 	} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

Here is the output of a sample run:

Class.forName Example

Class.forName Example Code Explanation:

Typically when we want to create an object we use statement like:

Around The World Flights - Promo Code WORLD15
Example ex = new Example();

But there might be situations where in you don’t know the class name before hand. That is what we are trying to simulate here. In this example code listed above, we create an object based on the class name given by the user at runtime.

1) The line below creates an object of type Class which we will use to encapsulates the class input by the user (com.quicklyjava.Example in this case).

Class exampleClass = Class.forName(whatClass);

2) The below line create an object of type Example (exampleClass encapsulates the class Example as seen in the previous point)

Object ob = exampleClass.newInstance();

This way, we are able to create objects dynamically at run time.

The most common application of this is in creating the JDBC connections.

e.g. See the code below:

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1565:myDB");

In this case, we get the connection object using DriverManager.getConnection irrespective of the database we are using. This is possbile because, Class.forName dynamically loads the required database driver class.

It is interesting to know that Class.forName loads the class passed to it as argument. It means it will execute static blocks of code if any in the loaded class.

You can download the eclipse project of the code explained in this tutorial:
ClassForNameDemo.zip (4KB)

Please consider following our blog (via Email, Twitter, Facebook and/or Google+ – See the right sidebar) for more interesting posts.

9 responses to “Class.forName Example”

  1. Cedrick Palek

    Good day! I could have sworn I’ve been to this website before but after going through some of the posts I realized it’s new to me. Anyways, I’m definitely pleased I discovered it and I’ll be bookmarking it and checking back frequently!

  2. venkatesh

    Class.forName(“oracle.jdbc.driver.OracleDriver”);
    Connection con = DriverManager.getConnection(“jdbc:oracle:thin:@127.0.0.1:1565:myDB”);

    You told that class.forName() is used when ever we dont know the class Name.

    Here the con object is created by DriverManager.getConnection(“url”) method what is the relation of using class.forName() here ,i am confused .can u plz explain

  3. Balusamy

    Nice one

  4. santhanam

    very good explaination.please give more examples like this!

  5. siva

    Suppose if we use multiple times class.forName in the same class .
    What will happen?
    class A{
    Void method1(){
    try{
    Class.forName(“oracle.jdbc.driver.OracleDriver”);
    }
    catch(){}
    }
    void method2(){
    try{
    Class.forName(“oracle.jdbc.driver.OracleDriver”);
    }
    catch(){}
    }
    public static void main(String arg[]){
    A a=new A();
    a.method1();
    a.method2();
    }
    }

  6. Bhagya

    Thanks a lot! it helped a lot!

  7. priyanka

    In class called “class”, forName is a method, that method is called in static block so it will load at only once. Because if we call any method in static block it wil call only once.

  8. Chandan Karmakar

    Very clear and detailed explanation.
    Thanks a ton. :)

Leave a Reply