Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the work of ClassLoader loadClass()

Tags:

java

I have writen the small java class which I want to load by 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 find that the static block does not get executed. My question is that if a class is loaded by using the loadClass() method, why are static blocks not executed in comparison to instantiating a class where static blocks always get executed.

like image 500
Jon Avatar asked Oct 19 '22 19:10

Jon


1 Answers

Actually static block gets executed when the class is initialized and it's a little bit different from loaded.

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

Here is well described how it works and what are the requirements for a class to become initialized.

An excerpt:

The Java virtual machine specification gives implementations flexibility in the timing of class and interface loading and linking, but strictly defines the timing of initialization. All implementations must initialize each class or interface on its first active use. The following six situations qualify as active uses:

  • A new instance of a class is created (in bytecodes, the execution of a new instruction. Alternatively, via implicit creation, reflection, cloning, or deserialization.)
  • The invocation of a static method declared by a class (in bytecodes, the execution of an invokestatic instruction)
  • The use or assignment of a static field declared by a class or interface, except for static fields that are final and initialized by a compile-time constant expression (in bytecodes, the execution of a getstatic or putstatic instruction)
  • The invocation of certain reflective methods in the Java API, such as methods in class Class or in classes in the java.lang.reflect package
  • The initialization of a subclass of a class (Initialization of a class requires prior initialization of its superclass.)
  • The designation of a class as the initial class (with the main()< method) when a Java virtual machine starts up
like image 159
davidluckystar Avatar answered Oct 22 '22 09:10

davidluckystar