[英]Initialization-on-demand holder idiom - When are classes loaded?
I have been looking at: https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom to understand a little bit more about Singletons. 我一直在看: https : //en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom来了解有关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.
我的理解是,可以加载类,但始终保持未初始化状态,直到绝对需要初始化为止。
If the class is not loaded, how is the private static inner class specified within the JVM? 如果未加载该类,那么如何在JVM中指定私有静态内部类?
The exact time when a class is initialized, is specified in the Java® Language Specification, §12.4.1 Java®语言规范§12.4.1中指定了初始化类的确切时间。
§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将在以下任何一种首次出现之前立即初始化:
T
is a class and an instance ofT
is created.T
是一个类,并创建T
的实例。- A
static
method declared byT
is invoked.调用由
T
声明的static
方法。- A
static
field declared byT
is assigned.分配由
T
声明的static
字段。- A
static
field declared byT
is used and the field is not a constant variable ( §4.12.4 ).使用由
T
声明的static
字段,并且该字段不是常量变量(第4.12.4节 )。T
is a top level class ( §7.6 ) and anassert
statement ( §14.10 ) lexically nested withinT
( §8.1.3 ) is executed.T
是一个顶级类(第7.6节 ),并执行一个词法嵌套在T
的assert
语句(第14.10节 )(第8.1.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).
初始化类时,将初始化其超类(如果之前尚未对其进行初始化),以及声明了任何默认方法的任何超接口(第8.1.5节 )(第9.4.3节 )(如果以前未对其进行初始化)。 )。 Initialization of an interface does not, of itself, cause initialization of any of its superinterfaces.
接口的初始化本身并不会导致其任何超级接口的初始化。
The last bullet has been removed in Java 9 Java 9中删除了最后一个项目符号
The time of class loading is not that fixed and may depend on implementation details, eg how the verifier has been implemented. 类加载的时间不是固定的,并且可能取决于实现细节,例如,验证程序的实现方式。 But obviously, it has to happen before the initialization.
但显然,它必须在初始化之前发生。
From the JVM's point of view, the fact that this is a nested class has no special relevance. 从JVM的角度来看,这是一个嵌套类这一事实没有特殊的意义。 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.
它将在需要时解决 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.