Is the Java class loaded if I access MyClass.class.getName ()?
I want to explicitly initialize some classes during initialization of my application with Class.forName
, but in order for this code to survive refactoring, I want to use this:
Class.forName(MyClass.class.getName());
I wonder if the class won't be loaded as soon as the method is executed getName
, making it unnecessary Class.forName
?
In fact, even a call is getName()
not needed, since the MyClass.class
class must be loaded and initialized for the object to exist .
Of course, this method means that you have a compile-time dependency on MyClass
that you do not have when used Class.forName()
with a string literal.
You can check this easily. Just add something like this:
static { System.out.println("Class loaded"); }
in class and try it. Static blocks are executed when the class is loaded.
I just found out: -verbose:class
Shows all class loading events.
As Michael Borgwardt says, the simplest expression to achieve your goal is MyClass.class
.
You might only want to assign the value returned to something if the compiler has ever decided that an operator has no side effects and can be optimized, but I don't think that's possible.