Java中的静态循环依赖

发布于 2024-11-16 11:15:36 字数 450 浏览 7 评论 0原文

对于以下代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

浮萍、无处依 2024-11-23 11:15:36

以下是按时间顺序发生的情况:

  1. Class B 包含 main-method,因此它由类加载器加载。

  2. B 的初始化引用 A,因此加载 A 类。

  3. A 有一个静态变量 X,初始化为 BY + 1

    BY的初始化尚未执行,因此BY的计算结果为0,因此1被分配给AX

  4. 现在 < code>A已完成加载,可以进行BY的初始化。

    AX + 1(1 + 1)的值赋给BY

  5. AXBY 的值分别打印为 12

进一步阅读:

Java语言规范,§12.4.1 初始化发生时

Here is what happens in chronological order:

  1. Class B contains the main-method so it is loaded by the class loader.

  2. Initialization of B references A, so class A is loaded.

  3. A has a static variable X initialized to B.Y + 1.

    The initialization of B.Y hasn't been executed yet, so B.Y evaluates to 0, and thus 1 is assigned to A.X

  4. Now A has finished loading, and the initialization of B.Y can take place.

    The value of A.X + 1 (1 + 1) is assigned to B.Y.

  5. The values of A.X and B.Y are printed as 1 and 2 respectively.

Further reading:

Java Language Specification, §12.4.1 When Initialization Occurs

毅然前行 2024-11-23 11:15:36

这只是我的猜测:

  1. 加载类 B 是因为它包含您请求执行的 main
  2. 加载器发现 B 需要 A 进行操作(它通过访问其静态字段来使用 A
  3. 类 >B 已加载。
  4. A需要类B,而该类恰好已经加载,但尚未初始化
  5. A不小心加载了BY(已初始化)默认情况下为 0),因为该类看起来已加载(语言设计缺陷?)
  6. AX = 0 + 1
  7. A 现在已加载,类加载器可以继续加载并初始化B
  8. BY = 1 + 1

This is only my guess:

  1. Class B is loaded because it contains main which you have requested to be executed.
  2. Class loader discovers that B requires A to operate (it uses A by accessing its static field)
  3. Class B is loaded.
  4. Class A requires class B which happens to be already loaded, but not yet initialized
  5. A carelessly loads B.Y (initialized to 0 by that time by default), since the class looks like loaded (language design flaw?)
  6. A.X = 0 + 1
  7. A is now loaded, class loader can continue to load and initialize B
  8. B.Y = 1 + 1.
因为看清所以看轻 2024-11-23 11:15:36

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文