Does this two Java statement lookup the class in the same way?
this.getClass().getClassLoader().loadClass("Foo");
and
Class.forName("Foo");
Does this two Java statement lookup the class in the same way?
this.getClass().getClassLoader().loadClass("Foo");
and
Class.forName("Foo");
They're different: even though they use the same class loader (see forName()
documentation) loadClass()
does not run static initializers while forName()
does.
This is easily demonstrated with the following classes:
public class ClassA {
static {
System.out.println("ClassA static initializer");
}
public ClassA() {}
}
and
public class ClassB {
private ClassB() {}
private void loadStuff(boolean initialize) throws ClassNotFoundException {
if (initialize) {
Class.forName("ClassA");
} else {
this.getClass().getClassLoader().loadClass("ClassA");
}
}
public static void main(String[] args) throws ClassNotFoundException {
ClassB b = new ClassB();
b.loadStuff(true); // Try also false
}
}
Running ClassB
passing true to loadStuff()
will display "ClassA static initializer" while running it passing false to loadStuff()
doesn't display anything.
Of course, if you subsequently instantiate the loaded class its static initializer will be run if it has not yet been executed. In this case the difference between the two methods of loading a class is in the time when static initializers are run.
Here is interesting discussion on this topic. Class.forName() vs ClassLoader.loadClass() - which to use for dynamic loading? to-use-for-dynamic-loading