加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 静态初始化块的顺序

发布时间:2020-12-15 02:54:28 所属栏目:Java 来源:网络整理
导读:我在静态初始化块上发现了很多帖子,但是我试图更好地了解执行顺序及其原因.下面的代码打印出两个静态块中的文本,然后“then”打印出主静态块中的文本. 我理解编译器调用它的方式是在加载类时按顺序执行所有静态块,然后访问main方法.但是由于main方法本身是静
我在静态初始化块上发现了很多帖子,但是我试图更好地了解执行顺序及其原因.下面的代码打印出两个静态块中的文本,然后“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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读