gpt4 book ai didi

Java 静态初始化顺序

转载 作者:IT老高 更新时间:2023-10-28 20:34:37 26 4
gpt4 key购买 nike

我试图找出初始化发生的顺序,或者更确切地说,初始化按此顺序发生的原因。给定代码:

public class Main {

{
System.out.printf("NON-STATIC BLOCK\n");
}

static{
System.out.printf("STATIC BLOCK\n");
}

public static Main m = new Main();

public Main(){
System.out.printf("MAIN CONSTRUCTOR\n");
}

public static void main(String... args) {
//Main m = new Main();
System.out.printf("MAIN METHOD\n");

}
}

输出:

STATIC BLOCK

NON-STATIC BLOCK

MAIN CONSTRUCTOR

MAIN METHOD

但是,在初始化 block 之前移动 m 的声明会产生:

NON-STATIC BLOCK

MAIN CONSTRUCTOR

STATIC BLOCK

MAIN METHOD

我完全不知道为什么它会以这种顺序出现。此外,如果我在 m 的声明中删除 static 关键字,init block 和构造函数都不会触发。谁能帮我解决这个问题?

最佳答案

我认为你只是缺少 section 12.4.2 of the JLS ,其中包括:

Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.

“按文本顺序”部分是重要的部分。

如果您将 m 从静态变量更改为实例变量,则该字段将不会被 class 初始化 - 它只会被 < em>instance 初始化(即构造实例时)。目前,这会导致堆栈溢出——创建一个实例需要创建另一个实例,这需要创建另一个实例,等等。

编辑:同样section 12.5指定实例初始化,包括以下步骤:

  • Execute the instance initializers and instance variable initializers for this class, assigning the values of instance variable initializers to the corresponding instance variables, in the left-to-right order in which they appear textually in the source code for the class. If execution of any of these initializers results in an exception, then no further initializers are processed and this procedure completes abruptly with that same exception. Otherwise, continue with step 5.

  • Execute the rest of the body of this constructor. If that execution completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, this procedure completes normally.

这就是为什么您会在“主构造器”之前看到“非静态 block ”。

关于Java 静态初始化顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19058766/

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