I'm not sure what's the difference of loading static variables/blocks between MyClass.class
and Class.forName("MyClass")
, for example, I have below class:
package test;
public class SampleClass{
public static SampleClass instance = new SampleClass();
private SampleClass(){
System.out.println("SampleClass Instance Created");
}
}
Then, in another class, I accessed the class object of above SampleClass by using:
System.out.println(SampleClass.class);
Then, the output will be:
class test.SampleClass
If I changed to use class.forName()
, as below:
System.out.println(Class.forName("test.SampleClass"));
Then, the output will be:
SampleClass Instance Created
class test.SampleClass
Does anybody can give me an explanation? Thanks a lot.
The call to the Class.forName("MyClass")
causes the class to be loaded at runtime. JVM also initializes that class after the class has been loaded by the classloader, so static
blocks get executed.
In your case you have a static field which is the instance of your class, as this static block get executed your object is being initialized. That's why you are seeing the System.out get printed.
The .class
syntax is used to get the Class
of the called class. It doesn't not load the class actually.
Class.forName()
uses the ClassLoader and tries to resolve class name at runtime, while .class
is resolved at compile time.
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