Difference between Loading a class using ClassLoader and Class.forName

The other answers are very complete in that they explore other overloads of Class.forName(...), and talk about the possibility to use different ClassLoaders.

However they fail to answer your direct question: “What is the difference between the above said approaches?”, which deals with one specific overload of Class.forName(...). And they miss one very important difference. Class initialization.

Consider the following class:

public class A {
  static { System.out.println("time = " + System.currentTimeMillis()); }
}

Now consider the following two methods:

public class Main1 {
  public static void main(String... args) throws Throwable {
    final Class<?> c = Class.forName("A");
  }
}

public class Main2 {
  public static void main(String... args) throws Throwable {
    ClassLoader.getSystemClassLoader().loadClass("A");
  }
}

The first class, Main1, when run, will produce an output such as

time = 1313614183558

The other, however, will produce no output at all. That means that the class A, although loaded, has not been initialized (ie, it’s <clinit> has not been called). Actually, you can even query the class’s members through reflection before the initialization!

Why would you care?

There are classes that performs some kind of important initialization or registration upon initialization.

For example, JDBC specifies interfaces that are implemented by different providers. To use MySQL, you usually do Class.forName("com.mysql.jdbc.Driver");. That is, you load and initialize the class. I’ve never seen that code, but obviously the static constructor of that class must register the class (or something else) somewhere with JDBC.

If you did ClassLoader.getSystemClassLoader().loadClass("com.mysql.jdbc.Driver");, you would not be able to use JDBC, since the class, altough loaded, has not been initialized (and then JDBC wouldn’t know which implementation to use, just as if you had not loaded the class).

So, this is the difference between the two methods you asked.

Leave a Comment