gpt4 book ai didi

java - 按需初始化持有者习语 - 何时加载类?

转载 作者:行者123 更新时间:2023-11-30 02:10:15 27 4
gpt4 key购买 nike

我一直在看:https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom了解更多有关单例的信息。

我的问题是静态内部类到底什么时候被加载以及什么时候被初始化?我的理解是,可以加载类,但在绝对需要初始化之前保持未初始化状态。

如果类没有加载,那么JVM内部如何指定私有(private)静态内部类?

最佳答案

类初始化的确切时间在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.

最后一个项目符号已在 Java 9 中删除

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

从 JVM 的角度来看,这是一个嵌套类这一事实没有特殊的相关性。外部类中有对内部类的符号引用’ constant pool ,就像任何其他引用的类一样。它将是 resolved当需要时。

关于java - 按需初始化持有者习语 - 何时加载类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50339119/

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