问题描述
可能的重复:
Java 静态类初始化
为什么在初始化块中更新的是字符串变量而不是整数(即使块是先写入的)
Why is the string variable updated in the initialization block and not the integer(even though the block is written first)
class NewClass
{
static
{
System.out.println(NewClass.string+" "+NewClass.integer);
}
final static String string="static";
final static Integer integer=1;
public static void main(String [] args)//throws Exception
{
}
}
我的输出是
static null
P.S:还注意到只有当我插入最终修饰符时,字符串变量初始化才会在块之前发生.为什么会这样?为什么不是整数?我也将其声明为最终静态
P.S:Also noticed that string variable initialization happens before the block only when i insert the final modifier. why is that?why not for integer as well?I have declared it as final static too
推荐答案
来自 JLS 的第 12.4.2 节,适当剪下:
初始化C的过程如下:
然后,初始化其值为编译时常量表达式的最终类变量和接口字段(第 8.3.2.1 节、第 9.3.1 节、第 13.4.9 节、第 15.28 节).
Then, initialize the final class variables and fields of interfaces whose values are compile-time constant expressions (§8.3.2.1, §9.3.1, §13.4.9, §15.28).
接下来,按文本顺序执行类的类变量初始值设定项和静态初始值设定项,或接口的字段初始值设定项,就好像它们是单个块一样.
Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.
因此对于非编译时常量,它不是所有变量"的情况;然后是所有静态初始值设定项"反之亦然 - 所有这些都按文本顺序放在一起.所以如果你有:
So for non-compile-time-constants, it's not a case of "all variables" and then "all static initializers" or vice versa - it's all of them together, in textual order. So if you had:
static int x = method("x");
static {
System.out.println("init 1");
}
static int y = method("y");
static {
System.out.println("init 2");
}
static int method(String name) {
System.out.println(name);
return 0;
}
那么输出将是:
x
init 1
y
init 2
即使将 x
或 y
设为 final 也不会对这里产生影响,因为它们仍然不是编译时常量.
Even making x
or y
final wouldn't affect this here, as they still wouldn't be compile-time constants.
P.S:还注意到只有当我插入最终修饰符时,字符串变量初始化才会在块之前发生.
在这一点上,它是一个编译时常量,它的任何使用基本上都是内联的.此外,变量值在其余初始化器之前分配,如上.
At that point, it's a compile-time constant, and any uses of it basically inlined. Additionally, the variable value is assigned before the rest of the initializers, as above.
第 15.28 节JLS 定义了编译时常量 - 它包括所有原始值和 String
,但不包装器类型,例如 Integer
.
Section 15.28 of the JLS defines compile-time constants - it includes all primitive values and String
, but not the wrapper types such as Integer
.
这篇关于类中的静态块和静态变量以什么顺序执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!