When does static class initialization happen?(静态类初始化什么时候发生?)
问题描述
什么时候初始化静态字段?如果我从不实例化一个类,但我访问一个静态字段,那么用于实例化私有静态字段的所有静态块和私有静态方法是否都在那个时刻(按顺序)调用?
When are static fields initialized? If I never instantiate a class, but I access a static field, are ALL the static blocks and private static methods used to instantiate private static fields called (in order) at that instant?
如果我调用静态方法怎么办?它是否也运行所有静态块?在方法之前?
What if I call a static method? Does it also run all the static blocks? Before the method?
推荐答案
一个类的静态初始化通常发生在以下事件第一次发生之前:
A class's static initialization normally happens immediately before the first time one of the following events occur:
- 创建了一个类的实例,
- 调用类的静态方法,
- 分配了一个类的静态字段,
- 使用了非常量的静态字段,或者
对于顶级类,执行词法嵌套在类中的断言语句1.
请参阅 JLS 12.4.1.
也可以通过使用 Class.forName(fqn, true, classLoader)
或缩写形式 Class.forName(fqn)
It is also possible to force a class to initialize (if it hasn't already initialized) by using Class.forName(fqn, true, classLoader)
or the short form Class.forName(fqn)
1 - 最后一个要点出现在 Java 6 到 Java 8 的 JLS 中,但这显然是规范中的一个错误.它最终在 Java 9 JLS 中得到纠正:参见 source.
这篇关于静态类初始化什么时候发生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:静态类初始化什么时候发生?


基础教程推荐
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 降序排序:Java Map 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01