简体   繁体   中英

What is the work of ClassLoader loadClass()

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.

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

There are two types of class loader in java. Maybe the ClassLoader you use is the java.lang.ClassLoader, but the system won't use the this ClassLoader. You can try com.sun.org.apache.bcel.internal.util.ClassLoader.getSystemClassLoader(), it will execute the static block. More information you can reference to this page ( http://en.wikipedia.org/wiki/Java_Classloader#Class_Loaders_in_JEE )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM