I think the reason is that initializers are carried together with field initializations (and with constructors, in the case of instance initializers). In other words, the JVM only recognizes one place to initialize static fields, and thus all initializations - whether in blocks or not - must be done there.
So, for example, when you write a class:
class A {
static int x = 3;
static {
y = x * x;
}
static int z = x * x;
}
Then it's actually as if you've written:
class A {
static int x, y, z;
static {
x = 3;
y = x * x;
z = x * x;
}
}
This is confirmed if you look at the disassembly:
static {};
Code:
0: iconst_3
1: putstatic #5; //Field x:I
4: getstatic #5; //Field x:I
7: getstatic #5; //Field x:I
10: imul
11: putstatic #3; //Field y:I
14: getstatic #5; //Field x:I
17: getstatic #5; //Field x:I
20: imul
21: putstatic #6; //Field z:I
24: return
So if you would have added a "return" somewhere in the middle of your static initializer it would also have prevented z from being calculated.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…