Saturday 15 September 2018

Class.forName vs ClassLoader.loadClass

The main difference between Class.forName and ClassLoader.loadClass method is 'Class Initialization'.

When you load a class using ‘Class.forName’ method, it initialize the class by calling static block of the class.

DemoClass.java
package com.sample.model;

public class DemoClass {

 static {
  System.out.println("Initializing the class DemoClass");
 }

}

Application.java
package com.sample.app;

public class Application {

 public static void main(String args[]) throws Exception {
  Class.forName("com.sample.model.DemoClass");
 }
}

Output
Initializing the class DemoClass

When you load the class using ClassLoader, it will not call the static block of the class.

Application.java
package com.sample.app;

public class Application {

 public static void main(String args[]) throws Exception {
  Application.class.getClassLoader().loadClass("com.sample.model.DemoClass");
 }
}

When you ran Application.java, you will see nothing in the console.

You may like

No comments:

Post a Comment