Possible Duplicate:
Java static class initialization
为什么在初始化 block 中更新的是字符串变量而不是整数(即使 block 是先写的)
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: 还注意到,只有当我插入 final 修饰符时,字符串变量初始化才会发生在代码块之前。这是为什么?为什么不也用于整数?我也将其声明为最终静态
来自 section 12.4.2 JLS 的,适本地剪断:
The procedure for initializing C is then as follows:
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.
因此,对于非编译时常量,这不是“所有变量”然后“所有静态初始化器”的情况,反之亦然——它们都是按文本顺序排列在一起的。所以如果你有:
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 也不会影响这里,因为它们仍然不是编译时常量。
P.S:Also noticed that string variable initialization happens before the block only when i insert the final modifier.
此时,它是一个编译时常量,对它的任何使用基本上都是内联的。此外,如上所述,变量值在其余初始化器之前分配。
Section 15.28 JLS 的定义编译时常量 - 它包括所有原始值和 String
,但不包装器类型,例如 Integer
。