Use of Class.forName in java

In this article we will learn the uses of Class.forName in Java and how it is used in creating objects dynamically. In general Class.forName is used to load the class dynamically where we doesn’t know the class name before hand. Once the class is loaded we will use newInstance() method to create the object dynamically. Lets consider that we have a class “Test”, and we make a call like Class.forName(“com.javainterviewpoint.Test”), then Test class will be initialized (JVM will run the static block which is inside the Test Class).Class.forName(“com.javainterviewpoint.Test”) will returns a Class object associated with class Test.

Lets see the below example.

Test.java

Our Test class will have a static block and a public constructor.

package com.javainterviewpoint;

public class Test 
{
    static
    {
        System.out.println("Static block called");
    }
    public Test()
    {
        System.out.println("Inside Test class constructor");
    }

}

Logic.java

package com.javainterviewpoint;

import java.util.Scanner;

public class Logic 
{
    public static void main(String args[]) 
    {
        try {
            String someClassName = "";
            Scanner in = new Scanner(System.in);
            System.out.print("Please class name with package structure");
            someClassName = in.nextLine();       
            Class clasz = Class.forName(someClassName);
            Object obj = clasz.newInstance();
        }
        catch (ClassNotFoundException e) 
        {
            e.printStackTrace();
        } catch (InstantiationException e) 
        {
            e.printStackTrace();
        } catch (IllegalAccessException e) 
        {
            e.printStackTrace();
        }
    }
}

We may be in situations where in which you may know the class name before hand, then we can use the above way to create object at runtime. Lets see the explanation of the above code

Through Scanner we will get the class name with full package structure entered in the console.

Scanner in = new Scanner(System.in);
System.out.print("Please class name with package structure");
someClassName = in.nextLine();

The below line creates the object of type Class which encapsulates the class provided by the user.

Class clasz = Class.forName(someClassName);

The class Class has a method newInstance() which will create object for the class entered by the user(Test)

Object obj = clasz.newInstance();

Finally we have created the object dynamically for a class without knowing its name before hand.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s