gpt4 book ai didi

java - ClassLoader loadClass() 的工作是什么

转载 作者:搜寻专家 更新时间:2023-10-31 20:19:31 26 4
gpt4 key购买 nike

我已经编写了我想使用 ClassLoader 加载的小型 java 类。

public class ClassLoadingObj {

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

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

但是当我执行下面的代码时:

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

我发现静态 block 没有被执行。我的问题是,如果使用 loadClass() 方法加载类,与实例化始终执行静态 block 的类相比,为什么不执行静态 block 。

最佳答案

实际上静态 block 是在类初始化时执行的,它与加载有点不同。

初始化之前,类是链接,在此之前它是加载,所以有3个(或4个,包括未加载)状态类。

Here很好地描述了它是如何工作的,以及对一个类进行初始化的要求是什么。

节选:

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

关于java - ClassLoader loadClass() 的工作是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27902594/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com