java - Java中静态变量的文本顺序和初始化顺序

标签 java

我只花了五分钟在 SO 中找到重复项。

我的问题很简单。下面的代码总是有效吗?

public class LexicalOrderStatic {
    private static Integer a1 = initA1();

    private static Integer a2 = initA2();


    private static Integer initA2(){
        return new Integer(5) / a1;
    }

    private static Integer initA1(){
        return new Integer(5);
    }

    public Integer getA1(){
        return new Integer(a2);
    }

    public static void main(String[] args) {
        LexicalOrderStatic lexLuthor = new LexicalOrderStatic();
        System.out.println(lexLuthor.getA1());

    }
}

在 java 中,我可以确定 a1 总是在 a2 之前初始化吗?

谢谢。 dw 会问还是很简单就ok了。

最佳答案

In java can I be sure that a1 is always initialized before a2 ?

是的,因为规范(section 12.4.2)保证它(强调我的):

Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.

请注意,常量的初始化时间早于非常量(第 6 步与上面引用的第 9 步相比)。

关于java - Java中静态变量的文本顺序和初始化顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22219512/

相关文章:

java - Android 时间选择器弹出问题

Java Servlet 和其他项目引用

java - Hibernate 什么时候打印统计信息?

java - 如何通过java中的mouselisteners获取2D数组(jlabel)的索引?

java - Java 8 121 中需要 BouncyCasSTLe 吗?

java - 在 Android 中导入更新的 Apache HttpClient jar

java - 从 JPA 注释的实体类自动生成数据模式

java类只有声明没有定义

java - 如何更改已在数据库中注册的 id 列类型

java - 添加 ImageView 时应用程序崩溃