0

Does this two Java statement lookup the class in the same way?

this.getClass().getClassLoader().loadClass("Foo");

and

Class.forName("Foo");
Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
José
  • 3,041
  • 8
  • 37
  • 58
  • 1
    possible duplicate of [Class.forName() vs ClassLoader.loadClass() - which to use for dynamic loading?](http://stackoverflow.com/questions/8100376/class-forname-vs-classloader-loadclass-which-to-use-for-dynamic-loading) – Paul Bellora Dec 28 '11 at 20:32
  • By **"lookup"**, do you mean loading the class? – Bhesh Gurung Dec 28 '11 at 20:34
  • By lookup i mean the sources that are try to load the class – José Dec 28 '11 at 20:35
  • ClassLoader.getSystemClassLoader() can be different from the class classLoader, the class invoking it can be loaded from a custom class loader. – José Dec 28 '11 at 20:36
  • 1
    In your case, the second one, under the hood, uses the first one. Is that what you were trying to know? – Bhesh Gurung Dec 28 '11 at 20:39
  • Yes gurung that is what i want to know. – José Dec 28 '11 at 23:25

2 Answers2

3

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.

Adam Zalcman
  • 26,643
  • 4
  • 71
  • 92
-1

Here is interesting discussion on this topic. Class.forName() vs ClassLoader.loadClass() - which to use for dynamic loading? to-use-for-dynamic-loading

Community
  • 1
  • 1
kosa
  • 65,990
  • 13
  • 130
  • 167