类初始化
初始化时机:
初始化是执行 class 或 interface 的初始化方法 <init>
, 以下内容来自 JVM 文档 1 :
- 当执行这些虚拟机指令时: new T, 存取 T 的静态变量/方法
- new, 静态资源相关的 MethodHandle 实例被调用
- 一些反射方法被调用. 例如 Class 的方法
- T(T 是 class) 的子类被初始化
- T(T 是 interface) 的实现类被初始化
- T 是JVM启动时的初始化类
以下内容来自 Java 文档 2 :
- T is a class and an instance of T is created.
- 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.
循环依赖:
package com.lvw.jvm.init_class;
public class CircleInitializing {
public static void main(String[] args) {
int f = Sub.f;
}
static class Super {
static int f = 1; // 1
static {
// 2
System.out.println("Super is initializing.");
Sub.run(); // 3
System.out.println("Super was initialized.");
}
static void run() {
System.out.println("Super.run() was called.");
}
}
static class Sub extends Super {
// 4 recursive ini