gpt4 book ai didi

java - 递归初始化 : Static Initializer not getting called when i access Class field

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:59:45 25 4
gpt4 key购买 nike

关于加载类和调用静态初始化器的理解

In what order do static initializer blocks

所以,我只是想确认一下——

public class OOMErrorB extends OOMErrorA {
public static int c = 10;

static {
System.out.println("Loading static B " + c);
System.out.println(OOMErrorA.a);
}

public static void main(String[] args) {
new OOMErrorB();
}
}

父类是-

public class OOMErrorA {
public static int a = 20;

static {
a = a+ OOMErrorB.c;
System.out.println("OOMErrorB.c " + OOMErrorB.c);
System.out.println("loading OOMErrorA.a " + a);
}
}

现在B的main方法的输出-

**

OOMErrorB.c 0
loading OOMErrorA.a 20
Loading static B 10
20

**

我可以理解,首先它加载类 A,因为它是父类(super class)并调用它的静态初始化器,

现在因为我在 OOMErrorA 的静态 block 中访问 OOMErrorB.c,它应该加载并调用 OOMErrorB 的静态初始化程序。所以,OOMErrorB.c 应该是 10 而不是 0。

我对加载和初始化类的了解 -

1) Class and gets loaded and variables are initialized to default values like for int - 0, Object - null.
2) Class field are initialized to specified values.
3) Static block gets called .

在我的程序中,我可以看到类 OOMErrorB 已加载(第 1 步),但第 2 步和第 3 步没有执行。

而根据链接上接受的答案,它应该调用 OOMErrorB 的静态初始化程序。

所以它应该以循环依赖告终?

最佳答案

当访问 OOMErrorB.c 时,OOMErrorB 加载,因为它已经在加载过程中(当 JVM 最初加载时它是为了调用 main 方法)。 JVM 中一旦加载了一个类,就不会再次加载它。因此,不会出现循环依赖:OOMErrorB的静态成员c被fetch了,此时还没有初始化。

可以查看this section from the Java language specification关于类初始化:

Because the Java programming language is multithreaded, initialization of a class or interface requires careful synchronization, since some other thread may be trying to initialize the same class or interface at the same time. There is also the possibility that initialization of a class or interface may be requested recursively as part of the initialization of that class or interface; for example, a variable initializer in class A might invoke a method of an unrelated class B, which might in turn invoke a method of class A. The implementation of the Java Virtual Machine is responsible for taking care of synchronization and recursive initialization by using the following procedure.

JVM 有其正确的方法来锁定类的初始化,从而防止递归初始化。

关于java - 递归初始化 : Static Initializer not getting called when i access Class field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30142611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com