Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference static behaviour between MyClass.class and Class.forName(“MyClass”)

Tags:

java

class

static

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.

like image 864
user3709482 Avatar asked Mar 19 '23 10:03

user3709482


2 Answers

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.

Reference:

  • What does Class.forname method do?
  • Java Doc
  • Retrieving Class Object
like image 150
Tapas Bose Avatar answered Apr 25 '23 10:04

Tapas Bose


Class.forName() uses the ClassLoader and tries to resolve class name at runtime, while .class is resolved at compile time.

like image 39
vidit Avatar answered Apr 25 '23 08:04

vidit