我理解编译器调用它的方式是在加载类时按顺序执行所有静态块,然后访问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"); } }
实际产出
This block welcomes you first This block welcomes you after Meow world
为什么不?
This block welcomes you first Meow world This block welcomes you after
解决方法
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.