Java 静态初始化顺序

标签 java

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

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/

相关文章:

java - 删除随机生成的 UUID 中的 "-"有多安全?

java - Java 应用程序级别的关键事件

java - 将 JSON 数据转换为一组 Java 对象

java - 用于 CSV 上传的 Struts2 + Tomcat MIME 类型

java - 发送指定端口号的 HTTP POST 请求

java - 如何在 Eclipse 中使用 Lombok 生成复杂 json 的 pojo

java字节码类定义

java - 如果按下按钮,则重新启动我的 GUI

java - 尝试在浏览器上打开小程序时出现错误事件

java - 无法控制共享首选项中字符串集的顺序