Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

like image 596
Daniel Rikowski Avatar asked Nov 26 '25 23:11

Daniel Rikowski


2 Answers

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.

like image 100
Michael Borgwardt Avatar answered Nov 28 '25 13:11

Michael Borgwardt


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.

like image 22
del-boy Avatar answered Nov 28 '25 13:11

del-boy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!