java - 类中静态 block 和静态变量的执行顺序是什么?

标签 java static final

<分区>

Possible Duplicate:
Java static class initialization

为什么在初始化 block 中更新的是字符串变量而不是整数(即使 block 是先写的)

class NewClass
{
    static 
    {
       System.out.println(NewClass.string+" "+NewClass.integer);
    }

    final static String string="static";
    final static Integer integer=1;

    public static void main(String [] args)//throws Exception
    {
    }
}

我的输出是

static null

P.S: 还注意到,只有当我插入 final 修饰符时,字符串变量初始化才会发生在代码块之前。这是为什么?为什么不也用于整数?我也将其声明为最终静态

最佳答案

来自 section 12.4.2 JLS 的,适本地剪断:

The procedure for initializing C is then as follows:

  • Then, initialize the final class variables and fields of interfaces whose values are compile-time constant expressions (§8.3.2.1, §9.3.1, §13.4.9, §15.28).

  • 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.

因此,对于非编译时常量,这不是“所有变量”然后“所有静态初始化器”的情况,反之亦然——它们都是按文本顺序排列在一起的。所以如果你有:

static int x = method("x");

static {
    System.out.println("init 1");
}

static int y = method("y");

static {
    System.out.println("init 2");
}

static int method(String name) {
    System.out.println(name);
    return 0;
}

那么输出将是:

x
init 1
y
init 2

即使将 xy 设置为 final 也不会影响这里,因为它们仍然不是编译时常量。

P.S:Also noticed that string variable initialization happens before the block only when i insert the final modifier.

此时,它是一个编译时常量,对它的任何使用基本上都是内联的。此外,如上所述,变量值在其余初始化器之前分配。

Section 15.28 JLS 的定义编译时常量 - 它包括所有原始值和 String,但包装器类型,例如 Integer

关于java - 类中静态 block 和静态变量的执行顺序是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12448465/

相关文章:

java - 方法的final局部变量 'avoid repeat invocations'怎么办?

Java 泛型命名约定

java - 开发者环境——如何调用/消费其他微服务

java - 在 Java 中生成分区

android - Kotlin:伴随对象 lateinit vars 初始化一次吗?

java - 如何在静态 main 方法中将数据添加到数组列表中

Java静态方法内存分配

python - 如何防止函数在 Python 中被覆盖

java - 如何创建 JButton 数组?

flutter - Flutter:在无状态小部件中,我收到 “The instance member ' xy',无法在初始化程序中对其进行访问。”在数组xy上使用长度时