我在静态初始化块上发现了很多帖子,但是我试图更好地了解执行顺序及其原因.下面的代码打印出两个静态块中的文本,然后"then"打印出主静态块中的文本.
我理解编译器调用它的方式是在加载类时按顺序执行所有静态块,然后访问main方法.但是由于main方法本身是静态的,为什么不按照其他静态块的顺序执行它(甚至不确定它是否有用,只是试图理解一个概念,以及是否有这样做的紧迫原因).如果我们想在主块之后运行静态块怎么办?
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");
}
}
Run Code Online (Sandbox Code Playgroud)
实际产出
This block welcomes you first
This block welcomes you after
Meow world
Run Code Online (Sandbox Code Playgroud)
为什么不?
This block welcomes you first
Meow world
This block welcomes you after
Run Code Online (Sandbox Code Playgroud)
加载类后立即执行静态初始值设定项.在加载类之后main调用该方法.
JLS的这一部分讨论了事件的顺序(12.1.3-4):
12.1.3.初始化测试:执行初始化器
在我们的示例中,Java虚拟机仍在尝试执行类Test的方法main.只有在类已初始化(第12.4.1节)时才允许这样做.
初始化包括以文本顺序执行类Test的任何类变量初始化器和静态初始化器.但是在初始化Test之前,必须初始化它的直接超类,以及它的直接超类的直接超类,依此类推,递归.在最简单的情况下,Test将Object作为其隐式直接超类; 如果尚未初始化类Object,则必须在初始化Test之前初始化它.Class Object没有超类,因此递归终止于此.
12.1.4.调用Test.main
最后,在完成类Test的初始化之后(在此期间可能发生了其他相应的加载,链接和初始化),调用Test的方法main.
运行时系统保证按照它们在源代码中出现的顺序调用静态初始化块.别忘了,这个代码将在JVM加载类时执行.JVM将所有这些块组合成一个静态块然后执行.以下是我要提到的几点:
If you have executable statements in the static block, JVM will automatically execute these statements when the class is loaded into JVM.
If you’re referring some static variables/methods from the static blocks, these statements will be executed after the class is loaded into JVM same as above i.e., now the static variables/methods referred and the static block both will be executed.
Run Code Online (Sandbox Code Playgroud)
之后,main方法将执行.谢谢
| 归档时间: |
|
| 查看次数: |
470 次 |
| 最近记录: |