我有这段代码,我使用 -verbose:class 选项运行它来查看已加载的类。令我惊讶的是,它显示它加载了类 A1 和 A2,但静态 block 没有被调用。
有人可以解释一下这种行为
package P1;
import java.lang.reflect.InvocationTargetException;
public class DemoReflection {
static {
System.out.println("Loading Demo");
}
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException,
InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
System.out.println("A2 " + A2.class.getClassLoader().getClass());
System.out.println("Demo " + DemoReflection.class.getClassLoader().getClass());
System.out.println("A1 " + A1.class.getClassLoader().getClass());
}
}
class A1 {
static {
System.out.println("Loading A1");
}
}
class A2 extends A1 {
static {
System.out.println("Loading A2");
}
public A2() {
System.out.println("m2");
}
public void m1() {
System.out.println("m1");
}
}
class A3 {
static int a3Id = 3;
static {
System.out.println("Loading A3");
}
}
最佳答案
JLS §8.7说:
A static initializer declared in a class is executed when the class is initialized (§12.4.2).
那么初始化是什么意思呢?我们引用JLS §12.4.2 。这描述了详细的初始化过程。不过点JLS §12.4.1放在这里可能更合适。它说:
A class or interface type T will be initialized immediately before the first occurrence of any one of the following:T is a class and an instance of T is created. T is a class and a static method declared by T is invoked. A static field declared by T is assigned. A static field declared by T is used and the field is not a constant variable (§4.12.4). T is a top level class (§7.6), and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.
这些选项都不适用于您的情况,因此不会调用静态 block 。
关于java - 类加载、静态 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57058978/