What is the work of ClassLoader loadClass ()

I wrote a small java class that I want to load using ClassLoader.

public class ClassLoadingObj { public ClassLoadingObj(){ System.out.println("---instantiating ClassLoadingObj "); } static{ System.out.println("---Loading ClassLoadingObj"); } } 

But when I executed the following code:

 ClassLoader.getSystemClassLoader().loadClass("com.st.classLoader.ClassLoadingObj"); 

I found that the static block is not executing. My question is, if a class is loaded using the loadClass() method, why are static blocks not executed compared to creating an instance of the class in which static blocks are always executed.

+5
source share
2 answers

In fact, a static block is executed when the class is initialized , and it is slightly different from the loaded one .

Before the initialized class is bound , and before that it is loaded , there are 3 (or 4, including not loaded) states of the class.

There is well documented, how it works and what are the requirements for the class initialization.

Exposure:

The Java virtual machine specification provides the implementation with flexibility in choosing the loading time and layout of classes and the interface, but strictly defines the initialization time. All implementations should be initialized by each class or interface at its first active use. The following six situations qualify as active use:

  • A new instance of the class is created (in bytecodes, execution of a new instruction. Alternatively, by implicit creation, reflection, cloning or deserialization.)
  • Calling the static method declared by the class (in bytecodes, invokestatic instruction execution)
  • Use or assignment of a static field declared by a class or interface, with the exception of static fields that are final and initialized by expressing a compile-time constant (in bytecodes, executing the getstatic or putstatic statement)
  • Calling some reflective methods in the Java API, such as methods of the Class class or classes in the java.lang.reflect package
  • Initializing a subclass of a class (initializing a class requires first initializing its superclass.)
  • Designating a class as a source class (using the main () <method) when starting the Java virtual machine
+3
source

There are two types of class loader in java. Perhaps you are using ClassLoader java.lang.ClassLoader, but the system will not use this ClassLoader. You can try com.sun.org.apache.bcel.internal.util.ClassLoader.getSystemClassLoader (), it will execute a static block. Additional information that you can link to ( http://en.wikipedia.org/wiki/Java_Classloader#Class_Loaders_in_JEE )

0
source

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


All Articles