Load class with forName() method in Java

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 09-Jan-2019 10:55:29
Advertisements