JVM 静态初始化
Static initialization by JVM
语言:java
版本:12.0.2
字符串源码如下:
/* @implNote
* The actual value for this field is injected by JVM. The static
* initialization block is used to set the value here to communicate
* that this static final field is not statically foldable, and to
* avoid any possible circular dependency during vm initialization.
*/
static final boolean COMPACT_STRINGS;
static {
COMPACT_STRINGS = true;
}
如何理解这句话:'The static initialization block is used to set the value here to communicate that this static final field is not statically foldable, and to avoid any possible circular dependency during vm initialization.'
这是 JVM 实现者的实现说明。它不是 public 文档的一部分,使用 java.lang.String
的开发人员也不关心它。
但是如果你想知道:
假设他们写了:
static final boolean COMPACT_STRINGS = true;
那么编译器可以在任何使用 COMPACT_STRINGS
的地方用值 true
替换它(仅在 java.lang
包中,因为它是一个包-局部范围变量)
通过在静态初始值设定项中赋予它值 true
,编译器不再知道它是一个常量,所有使用它的代码都必须在运行时查找它的实际值.
在这种情况下,这很有用,因为 JVM 会在运行时更改此值(即使它是 final
,JVM 仍然可以更改它),如实施说明所述。
语言:java
版本:12.0.2
字符串源码如下:
/* @implNote
* The actual value for this field is injected by JVM. The static
* initialization block is used to set the value here to communicate
* that this static final field is not statically foldable, and to
* avoid any possible circular dependency during vm initialization.
*/
static final boolean COMPACT_STRINGS;
static {
COMPACT_STRINGS = true;
}
如何理解这句话:'The static initialization block is used to set the value here to communicate that this static final field is not statically foldable, and to avoid any possible circular dependency during vm initialization.'
这是 JVM 实现者的实现说明。它不是 public 文档的一部分,使用 java.lang.String
的开发人员也不关心它。
但是如果你想知道:
假设他们写了:
static final boolean COMPACT_STRINGS = true;
那么编译器可以在任何使用 COMPACT_STRINGS
的地方用值 true
替换它(仅在 java.lang
包中,因为它是一个包-局部范围变量)
通过在静态初始值设定项中赋予它值 true
,编译器不再知道它是一个常量,所有使用它的代码都必须在运行时查找它的实际值.
在这种情况下,这很有用,因为 JVM 会在运行时更改此值(即使它是 final
,JVM 仍然可以更改它),如实施说明所述。