Difference between Class.forName() and ClassLoader.loadClass()

Class.forName() and System.ClassLoader.loadClass() having big difference in context of loading class. You can understand it better by below examples

Class.forName() and System.ClassLoader.loadClass() Difference

Class.forName(“ClassName”)  :

  • Internally class ClassLoader.loadClass() that loaded the class.
  • It Initialize the class by using all static blocks in class.
  • In ClassLoader subsystem it executes all the three phases load, link and initialize phases.

For Example : In JDBC we use Class.forName(“Driver Name”) to load SQL Driver and register it.

ClassLoader.getSystemClassLoader().loadClass(“ClassName”):

  • Use system class Loader which is overridable to load class.
  • loadClass() method does not initialize the class. Class only will initialize when used for the first time.
  • in class loader subsystem loadClass() executes on two phases i.e load and link phases.

For Example : if we use ClassLoader.loadClass() method to load JDBC driver then only will load driver class but it will not register.

In below Java code you will understand how both ways of loading class are different because for same MyExampleClass, Class.forName() is intializing and  printing static block content while ClassLoader.getSystemClassLoader().loadClass() will only load the class and not initialize that’s why not printing anything in console.

public class MyExampleClass {
	    static {
	        System.out.println("Static Block in MyExampleClass");
	    }
}

public class ExampleLoader {

	public static void main(String[] args) {
		try {
			System.out.println("==========Result of Class.forName()===========");
			Class.forName("MyExampleClass");

			System.out.println("==========Result of ClassLoader.getSystemClassLoader().loadClass()===========");
			ClassLoader.getSystemClassLoader().loadClass("MyExampleClass");
		} catch (ClassNotFoundException ex) {
			ex.printStackTrace();
		}

	}

}

Output :

==========Result of Class.forName()===========
Static Block in MyExampleClass
==========Result of ClassLoader.getSystemClassLoader().loadClass()===========

Summary:

  • Explained about difference between loading of class for both methods  Class.forName() and ClassLoader.loadClass().
  • Loader sub systems phases cover in both the case.
  • Example of Class.forName() and ClassLoader.loadClass().
Advertisements

One thought on “Difference between Class.forName() and ClassLoader.loadClass()”

This site uses Akismet to reduce spam. Learn how your comment data is processed.