Class 正在加载,静态块

Class Loading, static block

我有这段代码,我 运行 它使用 -verbose:class 选项来查看加载的 classes。令我惊讶的是,它显示它已加载 class A1 和 A2,但未调用静态块。

谁能解释一下这种行为

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");
    }

}

输出:

简单版: 静态块仅在您第一次创建对象或访问该对象的静态成员时运行 class.

JLS §8.7 说:

A static initializer declared in a class is executed when the class is initialized (§12.4.2).

那么初始化是什么意思呢?在这里引用 JLS §12.4.2. This describes detailed initialization procedure. However point 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.
  • 这些选项均不适用于您的情况,因此不会调用静态块。