tags:

views:

255

answers:

4

I want to explicitly initialize some classes during the initialization of my application using Class.forName, but in order make that code survive refactorings, I want to use this:

Class.forName(MyClass.class.getName());

I wonder: Wouldn't the class be loaded as soon as the getName method is executed thus making Class.forName unnecessary?

+8  A: 

Actually, even the getName() call is unnecessary, since in order for the MyClass.class object to exist, the class has to be loaded and initialized.

Of course, this method means that you have a compile-time dependency on MyClass, which you do not have when using Class.forName() with a String literal.

Michael Borgwardt
It isn't necessary to initialise the class - otherwise the flag in the three-argument `Class.forName` would be pointless. As it turn out, IIRC, 1.5+ do not initialise the class (uses new for of `ldc` instruction); 1.4- do initialise the class (lazily uses single-argument `Class.forName` to store in a static).
Tom Hawtin - tackline
+6  A: 

You can easily check this out. Just add something like this:

static { System.out.println("Class loaded"); }

in the class and try it. Static blocks are executed when the class is loading.

del-boy
A: 

As Michael Borgwardt says, the simplest statement to achieve your aim is MyClass.class.

You might want to assign the value returned to something just in case the compiler ever decided that the statement had no side effects and could be optimized away, but I don't believe that any do.

Duncan McGregor
But as Michael also said, using MyClass.class adds a compile-time dependency on MyClass to your code, and you might not want that. If you just use Class.forName("org.mypackage.MyClass"), then you don't have a compile-time dependency.
Jesper
Well, if the OP wants to guard against refactactorings, then a compile-time dependency is exactly what he needs.
Michael Borgwardt
Eclipse has option: "Update textual occurrences in comments and strings" that would update class name in Class.forName statement. If he is using eclipse, that is...
del-boy
If you own the code that is being refactored you probably don't have a problem having a compile-time dependency on it.
Duncan McGregor
+3  A: 

I just found out: -verbose:class shows all class loading events.

DR