Create object/instance of class by name using Class.forName in java (examples)

  • Given an application in java.
  • We would like to create the instance of classes by specifying class name.
  • Instances of the class Class represent classes and interfaces in a running Java application.
  • We will get the reference of loaded class using Class.forName(“Complete path of a class”)
    • And then, we can create instance of loaded class.
  • Class Class does not have any public constructor.
    • Instead Class objects are constructed automatically by the Java Virtual Machine as classes are loaded.

1. What is purpose of Class.forName method?

  1. Class loader of an applications loads all classes.
  2. Class.forName returns the reference of Class objects for specified class name (Class loaded in step 1).
  3. We can created the instance of a class by using reference returned in step 2.

2. Examples: create object/instance of class by name (Class.forName/java)

  1. We generally create of the instances of JDBC drivers by proving complete path of driver.
    • e.g. Class<?> sqlDriver = Class.forName(“com.mysql.jdbc.Driver”);
  2. Let us look into the very simple example to create the instance of class ArrayList using class Class.
    1. Class<?> loadClass = Class.forName(“java.util.ArrayList”);
    2. ArrayList<String> arrayList = (ArrayList<String>) loadClass.newInstance();
    3. arrayList.add(“Item 0”);
    4. arrayList.add(“Item 1”);
  3. We will demonstrate various examples of class Class.
    1. We will create instance of Standard JDK class like ArrayList.
    2. We will create the instance thread in java using class Class.
    3. Create instance of User defined classes.
      1. We will create couple of custom classes.
      2. We will create their instance of custom classes using class Class.
      3. We will create objects USCitizen & SwissCitizen classes using newInstance() method.
create class forname java example
Fig 1: User defined objects

3. Program: create object/instance of class by name (Class.forName/java)

1. Citizen interface:

  • Citizen interface defines the couple of methods.
  • We will create couple of concrete class like USCitizen & SwissCitizen to implement Citizen interface.
package org.learn;

public interface Citizen {
    void nationality();
    void identity();
}

2. USCitizen class:

  • USCitizen class implements Citizen interface.
  • Complete code of USCitizen class is as follows:
package org.learn;

import java.util.Random;
import java.util.UUID;

public class USCitizen implements Citizen {

    public void nationality() {
        System.out.println("I am US Citizen");
    }

    public void identity() {
        Random random = new Random();
        random.nextInt();
        System.out.println("My identification number : "+random.nextInt());

    }
}

3. SwissCitizen class:

  • SwissCitizen class implements Citizen interface.
  • Complete code of SwissCitizen class is as follows:
package org.learn;

import java.util.UUID;

public class SwissCitizen implements Citizen {


    public void nationality() {
        System.out.println("I am Switzerland Citizen");
    }

    public void identity() {
        System.out.println("My identification number : "+UUID.randomUUID().toString());
    }
}

4. MyThread class:

  • We will create concrete  thread class extending from JDK Thread class.
  • Complete code of MyThread class is as follows:
package org.learn;

public class MyThread extends Thread {

    @Override
    public void run() {

        System.out.println("Thread started :");
        int index = 0;
        while (index++ < 10) {
            System.out.println("Iteration "+ index);

            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                break;
            }
        }
        System.out.println("Thread executed successfully");
    }

}

5. DemoForClassName class:

  • We will take 3 examples to demonstrate Class.forName concept.
    • Example 1: demoJDKClasses
      • Create the instance of standard JDK class ArrayList
    • Example 2: demoUserDefinedObjects
      • We will create objects of User defined classes.
        • USCitizen class implementing Citizen class.
        • SwissCitizen class implementing Citizen class.
    • Example 3: demoCreateThread
      • We will create custom thread class by extending Thread class.
  • The complete code of DemonForClassName class is as follows:
package org.learn;

import java.util.ArrayList;

public class DemoForClassName {

    public static void main(String[] args) throws IllegalAccessException,
            InstantiationException, ClassNotFoundException, InterruptedException {

        System.out.println("1. Start Invoking methods of ArrayList class");

        //Demo Standard JDK class like Integer
        demoJDKClasses();

        System.out.println("2. End invoke methods of ArrayList class");
        System.out.println();

        System.out.println("3. Start - Create user defined (Citizen) objects ");
        //Demo to custom user defined objects
        demoUserDefinedObjects();
        System.out.println("4. End -  Create user defined (Citizen) objects ");
        System.out.println();

        System.out.println("5. Create thread in java using class.forName");
        //Invoke methods of thread class in java
        demoCreateThread();
        System.out.println("6. End creating thread using class.forName");
    }

    private static void demoJDKClasses() throws ClassNotFoundException,
            IllegalAccessException, InstantiationException {

        //Load ArrayList class
        Class<?> loadClass = Class.forName("java.util.ArrayList");

        //Create instance of ArrayList class
        ArrayList arrayList = (ArrayList) loadClass.newInstance();

        arrayList.add("Item 0");
        arrayList.add("Item 1");

        //Print attributes of ArrayList class
        System.out.printf("Items in arrayList : %s, size  : %d\n",
                arrayList.toString(), arrayList.size());

    }

     private static void demoUserDefinedObjects() throws ClassNotFoundException,
            IllegalAccessException, InstantiationException {

        System.out.println("3.1 Invoke methods of USCitizen class");

        //Load USCitizen class
        Class<?> loadClass = Class.forName("org.learn.USCitizen");

        //Create instance of USCitizen class
        Citizen citizen = (Citizen) loadClass.newInstance();

        //Invoke method of class
        citizen.nationality();
        citizen.identity();

        System.out.println();
        System.out.println("3.2 Invoke methods of SwissCitizen class");

        //Load Swiss Citizen class
        loadClass = Class.forName("org.learn.SwissCitizen");

        //Create instance of Swiss citizen class
        citizen = (Citizen) loadClass.newInstance();

        //Invoke method of class
        citizen.nationality();
        citizen.identity();
    }

    private static void demoCreateThread() throws ClassNotFoundException,
            IllegalAccessException, InstantiationException, InterruptedException {

        //Load MyThread class
        Class<?> loadClass = Class.forName("org.learn.MyThread");

        //Create instance of Thread class
        Thread thread = (Thread) loadClass.newInstance();
        //Start thread
        thread.start();
        //Wait for completion of thread execution
        thread.join();
    }
}

4. Output: create object/instance of class by name (Class.forName/java)

1. Start Invoking methods of ArrayList class
Items in arrayList : [Item 0, Item 1], size  : 2
2. End invoke methods of ArrayList class

3. Start - Create user defined (Citizen) objects 
3.1 Invoke methods of USCitizen class
I am US Citizen
My identification number : -1165991133

3.2 Invoke methods of SwissCitizen class
I am Switzerland Citizen
My identification number : 86a5b53d-ac52-426f-a494-987d2ad69eac
4. End -  Create user defined (Citizen) objects 

5. Create thread in java using class.forName
Thread started :
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Iteration 6
Iteration 7
Iteration 8
Iteration 9
Iteration 10
Thread executed successfully
6. End creating thread using class.forName

 

Download code – create instance/objects using Class.forName java example

 

Scroll to Top