gpt4 book ai didi

java - 静态初始化 block 的顺序

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:45:37 26 4
gpt4 key购买 nike

我发现了很多关于静态初始化 block 的帖子,但是我试图更好地了解执行顺序及其原因。下面的代码打印出两个静态 block 中的文本,然后“然后”打印出主静态 block 中的文本。

我理解编译器调用它的方式是在加载类时按顺序执行所有静态 block ,然后访问 main 方法。但是由于 main 方法本身是静态的,为什么不按照其他静态 block 的顺序执行它(甚至不确定它是否有用,只是试图理解一个概念,以及是否有紧迫的理由以这种方式完成)。如果我们想在主 block 之后运行静态 block 怎么办?

class Cat {

static
{
System.out.println("This block welcomes you first");
}

public static void main(String[] args)
{
System.out.println("Meow world ");
}

static
{
System.out.println("This block welcomes you after");
}
}

实际输出

This block welcomes you first
This block welcomes you after
Meow world

为什么不呢?

This block welcomes you first
Meow world
This block welcomes you after

最佳答案

静态初始化器在类加载后立即执行。 main 方法在类加载后被调用。

JLS 的这一部分讨论了事件的顺序 (12.1.3-4):

12.1.3. Initialize Test: Execute Initializers

In our continuing example, the Java Virtual Machine is still trying to execute the method main of class Test. This is permitted only if the class has been initialized (§12.4.1).

Initialization consists of execution of any class variable initializers and static initializers of the class Test, in textual order. But before Test can be initialized, its direct superclass must be initialized, as well as the direct superclass of its direct superclass, and so on, recursively. In the simplest case, Test has Object as its implicit direct superclass; if class Object has not yet been initialized, then it must be initialized before Test is initialized. Class Object has no superclass, so the recursion terminates here.


12.1.4. Invoke Test.main

Finally, after completion of the initialization for class Test (during which other consequential loading, linking, and initializing may have occurred), the method main of Test is invoked.

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

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