java – 静态初始化块的顺序

前端之家收集整理的这篇文章主要介绍了java – 静态初始化块的顺序前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在静态初始化块上发现了很多帖子,但是我试图更好地了解执行顺序及其原因.下面的代码打印出两个静态块中的文本,然后“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");
    }
}

实际产出

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.

原文链接:https://www.f2er.com/java/128175.html

猜你在找的Java相关文章