views:

80

answers:

1
+1  Q: 

java reflection

Does anyone knows what is the different between:

Class clazz = getClass().getClassLoader().loadClass(className);

AND

Class clazz = Class.forName(className);

As i tried both, it gave me same result.

+6  A: 

Class.forName(className) execute the static initializer code blocks in the loaded class.

A call to forName("X") causes the class named X to be initialized.

getClass().getClassLoader().loadClass(className) doesn't.


Class.forName(className, false, getClass().getClassLoader()) is the same as getClass().getClassLoader().loadClass(className).


Resources :

Colin Hebert
Now that would be _really_ strange - you could get a class token of an uninitialized class via `ClassLoader.loadClass()`? How and when would that class supposed to get initialized then? I have serious doubts about any such difference.
Péter Török
When you load a class you don't initialize it, so it will be initialized when you'll use it (same behavior as other classes hard coded)
Colin Hebert
OK, I checked it further and you are right. +1 for you :-) For reference: http://java.sun.com/docs/books/jls/third_edition/html/execution.html#57946
Péter Török