Load class with forName() method in Java


The class object associated with the class with the given string name can be returned with the method java.lang.Class.forName(String name, boolean initialize, ClassLoader loader), using the class loader that is used to load the class.

The parameters in the forName() method are name, initialize and loader. If the value of the parameter loader is null, then the class is loaded using the bootstrap class loader. Also, if the initialize parameter is true, then only the class is initialized if it has not been initialized earlier.

A program that loads the class using the forName() method is given as follows −

Example

 Live Demo

import java.lang.*;
public class Demo {
   public static void main(String[] args) {
      try {
         Class c1 = Class.forName("Demo");
         ClassLoader classLoader = c1.getClassLoader();
         Class c2 = Class.forName("java.lang.String", true, classLoader);
         System.out.println("Class = " + c1.getName());
         System.out.println("Class = " + c2.getName());
      }
      catch(ClassNotFoundException e) {
         System.out.println("Excepton: " + e.toString());
      }
   }
}

Output

Class = Demo
Class = java.lang.String

Updated on: 25-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements