Daniel Rikowski
Daniel Rikowski

Reputation: 72504

Does a Java class get loaded if I access MyClass.class.getName()?

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?

Upvotes: 2

Views: 681

Answers (4)

Daniel Rikowski
Daniel Rikowski

Reputation: 72504

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

Upvotes: 3

Duncan McGregor
Duncan McGregor

Reputation: 18157

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.

Upvotes: 0

del-boy
del-boy

Reputation: 3654

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.

Upvotes: 6

Michael Borgwardt
Michael Borgwardt

Reputation: 346260

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.

Upvotes: 8

Related Questions