最终字段初始化顺序

最终字段初始化顺序

本文介绍了最终字段初始化顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一些在尚未初始化的类上调用静态方法A.f()的代码。
有人可以用JLS来解释这段代码的行为吗?

  A类{
final static Object b = new B();
final static int S1 = 1;
final static Integer S2 = 2;

static void f(){
System.out.println(S1);
System.out.println(S2);
}
}

B类{
static {
A.f();
}
}

公共类App
{
public static void main(String [] args)
{
Af ();
}
}

输出:

  1 
null
1
2


解决方案

af() in App.main()触发类的初始化 A



初始化所有常量变量。唯一的常量变量是 S1 ,现在 1



然后,其他静态字段按文本顺序初始化。 b 是第一个字段,它触发类 B 的初始化,后者又调用 Af () S2 只是 null 因为它尚未初始化。 b 的初始化现已完成。最后但并非最不重要的是, S2 初始化为整数对象 2



S2 不是常量变量,因为它不是原始类型 int 但引用类型 Integer S2 = 2; 的自动装箱速记,S2 = Integer.valueOf(2);


Here is some code that calls static method A.f() on class that is not initialized yet.Can someone explain behavior of this code in terms of JLS?

class A {
    final static Object b = new B();
    final static int S1 = 1;
    final static Integer S2 = 2;

    static void f() {
        System.out.println(S1);
        System.out.println(S2);
    }
}

class B {
    static {
        A.f();
    }
}

public class App
{
    public static void main( String[] args )
    {
        A.f();
    }
}

Output:

1
null
1
2
解决方案

A.f() in App.main() triggers initialization of class A.

All constant variables are initialized. The only constant variable is S1, which now is 1.

Then, the other static fields are initialized in textual order. b is the first field, which triggers initialization of class B, which in turn calls A.f(). S2 is simply null because it is not initialized yet. Initialization of b is now complete. Last but not least, S2 is initialized to the Integer object 2.

S2 is not a constant variable because it is not of the primitive type int but of the reference type Integer. S2 = 2; is an auto-boxing shorthand for S2 = Integer.valueOf(2);.

8.3.2. Field Initialization

4.12.4. final Variables

15.28. Constant Expressions

12.4.2. Detailed Initialization Procedure

4.12.5. Initial Values of Variables

这篇关于最终字段初始化顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 08:09