Initialization-on-demand holder 成语 - 类 何时加载?

Initialization-on-demand holder idiom - When are classes loaded?

我一直在看:https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom 以进一步了解单例。

我的问题是静态内部 class 究竟何时加载以及何时初始化?我的理解是 classes 可以加载但在绝对需要初始化之前保持未初始化状态。

如果不加载class,那么JVM内部如何指定private static inner class?

class 初始化的确切时间在 Java® Language Specification, §12.4.1

中指定

§12.4.1. When Initialization Occurs

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.
  • 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.

When a class is initialized, its superclasses are initialized (if they have not been previously initialized), as well as any superinterfaces (§8.1.5) that declare any default methods (§9.4.3) (if they have not been previously initialized). Initialization of an interface does not, of itself, cause initialization of any of its superinterfaces.

最后一个项目符号已在 Java9

中删除

class加载的时间不是那么固定,可能取决于实现细节,例如验证器是如何实现的。但显然,它必须在初始化之前发生。

从 JVM 的角度来看,这是一个嵌套 class 这一事实并没有什么特别的关联。需要的时候在外层class中有对内层class的符号引用'constant pool, like there is for any other referenced class. It will be resolved