Java中的静态循环依赖
对于以下代码:
class A
{
public static int X;
static { X = B.Y + 1;}
}
public class B
{
public static int Y = A.X + 1;
static {}
public static void main(String[] args) {
System.out.println("X = "+A.X+", Y = "+B.Y);
}
}
输出为:
X = 1, Y = 2
为什么?又如何呢?
PS:代码片段取自 JavaCamp.org
for the following code:
class A
{
public static int X;
static { X = B.Y + 1;}
}
public class B
{
public static int Y = A.X + 1;
static {}
public static void main(String[] args) {
System.out.println("X = "+A.X+", Y = "+B.Y);
}
}
the output is:
X = 1, Y = 2
Why? And How?
P.S: Code snippet taken from JavaCamp.org
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以下是按时间顺序发生的情况:
Class
B
包含 main-method,因此它由类加载器加载。B
的初始化引用A
,因此加载A
类。A
有一个静态变量X
,初始化为BY + 1
。BY
的初始化尚未执行,因此BY
的计算结果为0,因此1被分配给AX
现在 < code>A已完成加载,可以进行
BY
的初始化。将
AX + 1
(1 + 1)的值赋给BY
。AX
和BY
的值分别打印为1
和2
。进一步阅读:
Java语言规范,§12.4.1 初始化发生时
Here is what happens in chronological order:
Class
B
contains the main-method so it is loaded by the class loader.Initialization of
B
referencesA
, so classA
is loaded.A
has a static variableX
initialized toB.Y + 1
.The initialization of
B.Y
hasn't been executed yet, soB.Y
evaluates to 0, and thus 1 is assigned toA.X
Now
A
has finished loading, and the initialization ofB.Y
can take place.The value of
A.X + 1
(1 + 1) is assigned toB.Y
.The values of
A.X
andB.Y
are printed as1
and2
respectively.Further reading:
Java Language Specification, §12.4.1 When Initialization Occurs
这只是我的猜测:
B
是因为它包含您请求执行的main
。B
需要A
进行操作(它通过访问其静态字段来使用A
)A
需要类B
,而该类恰好已经加载,但尚未初始化A
不小心加载了BY
(已初始化)默认情况下为 0),因为该类看起来已加载(语言设计缺陷?)AX = 0 + 1
A
现在已加载,类加载器可以继续加载并初始化B
BY = 1 + 1
。This is only my guess:
B
is loaded because it containsmain
which you have requested to be executed.B
requiresA
to operate (it usesA
by accessing its static field)B
is loaded.A
requires classB
which happens to be already loaded, but not yet initializedA
carelessly loadsB.Y
(initialized to 0 by that time by default), since the class looks like loaded (language design flaw?)A.X = 0 + 1
A
is now loaded, class loader can continue to load and initializeB
B.Y = 1 + 1
.B 是公开的,开始自行加载。
看到 AX = BY +1 == 是从 0 开始(默认 int 对象值),因此是 1;
初始化 B = 1 + 1 = 2;
因此就有了答案。
B being public starts to load itself.
Sees A.X = B.Y +1 == which is 0 to start with (default int object value) hence 1;
initializes B = 1 + 1 = 2;
hence the answer.