Static difference behavior between MyClass.class and Class.forName ("MyClass")

I'm not sure if the difference in loading static variables / blocks is between MyClass.classand 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 above SampleClass using:

System.out.println(SampleClass.class);

Then the output will be:

class test.SampleClass

If I changed the usage class.forName()as shown below:

 System.out.println(Class.forName("test.SampleClass"));

Then the output will be:

 SampleClass Instance Created
 class test.SampleClass

Can anyone give me an explanation? Many thanks.

+4
source share
5 answers

The call Class.forName("MyClass")causes the class to load at run time. The JVM also initializes this class after the class has been loaded by the class loader, so the staticblocks are executed.

, , , . , System.out .

.class Class . .

:

+4

Class.forName() ClassLoader , .class - .

+2

class.forName() , "", .

.class .

+1

, Class.forName() (). ,

:

.forName( "X" ) X ( ). forName ( "X" ) X (.. JVM ). Class.forName( "X" ) Class, "X" . "x".

Class.forName( "X" ) , . JVM . - , . "X" - .

: http://www.xyzws.com/Javafaq/what-does-classforname-method-do/17

0
source

Thank you all for your answers and discussions.

I thought the class would be loaded regardless of using Class.forName () or MyClass.class, obviously I'm wrong. But I do not understand why it does not load the class when using MyClass.class.

0
source

Source: https://habr.com/ru/post/1543344/


All Articles