Java中的静态循环依赖 [英] Static Circular Dependency in 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
the output is: X = 1, Y = 2
为什么?和如何???
Why? and How???
-Ivar
PS:代码片段来自JavaCamp.org
P.S: Code snippet taken from JavaCamp.org
推荐答案
这是什么按时间顺序发生:
Here is what happens in chronological order:
-
Class
B
包含main方法所以它由类加载器加载。
Class
B
contains the main-method so it is loaded by the class loader.
初始化 B
引用一个
,所以加载了<$ p $ c> A 类。
Initialization of B
references A
, so class A
is loaded.
A
有一个静态变量 X
初始化为 BY + 1
。
A
has a static variable X
initialized to B.Y + 1
.
BY
的初始化尚未执行,因此 BY
评估为0,因此1分配给 AX
The initialization of B.Y
hasn't been executed yet, so B.Y
evaluates to 0, and thus 1 is assigned to A.X
现在
已完成加载,并且可以进行 BY
的初始化。
Now A
has finished loading, and the initialization of B.Y
can take place.
值 AX + 1
(1 + 1)分配给 BY
。
The value of A.X + 1
(1 + 1) is assigned to B.Y
.
AX
和 BY
的值打印为 1
并且分别为 2
。
The values of A.X
and B.Y
are printed as 1
and 2
respectively.
进一步阅读:
这篇关于Java中的静态循环依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!