按需初始化持有人惯用语-什么时候加载类? [英] Initialization-on-demand holder idiom - When are classes loaded?
问题描述
我一直在查看: https://en.wikipedia.org/wiki /Initialization-on-demand_holder_idiom 进一步了解Singleton.
I have been looking at: https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom to understand a little bit more about Singletons.
我的问题是静态内部类何时确切地被加载,什么时候被初始化?我的理解是,可以加载类,但是直到绝对必要进行初始化之前,它们都不会被初始化.
My question is when exactly does the static inner class get Loaded and when does it get Initialised? My understanding is that classes can be loaded but remain uninitialised until initialisation is absolutely necessary.
如果未加载该类,那么如何在JVM中指定私有静态内部类?
If the class is not loaded, how is the private static inner class specified within the JVM?
推荐答案
The exact time when a class is initialized, is specified in the Java® Language Specification, §12.4.1
§12.4.1.初始化何时发生
T的类或接口类型T会在以下任何一种首次出现之前立即初始化:
§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
是一个类,并创建了T
的实例. - 调用由
T
声明的static
方法. - 分配了
T
声明的static
字段. - 使用由
T
声明的static
字段,并且该字段不是常量变量(§14.10)按词法嵌套在T
(
T
is a class and an instance ofT
is created.- A
static
method declared byT
is invoked. - A
static
field declared byT
is assigned. - A
static
field declared byT
is used and the field is not a constant variable (§4.12.4). T
is a top level class (§7.6) and anassert
statement (§14.10) lexically nested withinT
(§8.1.3) is executed.
初始化一个类时,将初始化其超类(如果之前尚未初始化)以及任何超级接口(§9.4.3)(如果以前未对其进行初始化) .接口的初始化本身不会导致其任何超级接口的初始化.
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中删除
加载类的时间不是固定的,并且可能取决于实现细节,例如验证程序的实施方式.但是显然,它必须在初始化之前发生.
The time of class loading is not that fixed and may depend on implementation details, e.g. how the verifier has been implemented. But obviously, it has to happen before the initialization.
从JVM的角度来看,这是一个嵌套类这一事实没有特殊的意义.在外部类的常量池,就像其他任何引用的类一样.将已解决必要时.
From the JVM’s point of view, the fact that this is a nested class has no special relevance. There is a symbolic reference to the inner class in the outer class’ constant pool, like there is for any other referenced class. It will be resolved when needed.
这篇关于按需初始化持有人惯用语-什么时候加载类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!