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.
这篇关于静态类初始化什么时候发生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:静态类初始化什么时候发生?
基础教程推荐
- 存储 20 位数字的数据类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
