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

?

+2


source to share


4 answers


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.

+8


source


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.

+6


source


I just found out: -verbose:class

Shows all class loading events.

+3


source


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.

0


source







All Articles