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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With