按需初始化持有人惯用语-什么时候加载类? [英] Initialization-on-demand holder idiom - When are classes loaded?

查看:75
本文介绍了按需初始化持有人惯用语-什么时候加载类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在查看: 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 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中删除

加载类的时间不是固定的,并且可能取决于实现细节,例如验证程序的实施方式.但是显然,它必须在初始化之前发生.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆