gpt4 book ai didi

java - 当静态变量处于 RIWO 状态时,是否可以直接访问它?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:35:23 30 4
gpt4 key购买 nike

如果静态变量处于 RIWO(只读间接只写)状态。静态变量不能直接访问。

这是代码

class Test {
static{
System.out.println(x);
}

static int x = 10;

public static void main(String[] args) {

}
}

在这种情况下非法前向引用编译时错误来了。

但是如果是用类名访问静态变量,是可以访问的。

这里是代码示例

class Test {
static{
System.out.println(Test.x);
}

static int x = 10;

public static void main(String[] args) {

}
}

答案是:0

这怎么可能?这不是直接访问吗?

最佳答案

根据 JLS 12.4.1. When Initialization Occursthis answer :

a class's static initialization normally happens immediately before the first time one of the following events occur:

  • an instance of the class is created
  • a static method of the class is invoked
  • a static field of the class is assigned
  • a non-constant static field is used

在您的情况下,阅读 Test.x 属于第 4 点,一个非常量静态字段。您的代码读取并输出 0,这是默认的 int 值,但是您可以通过将字段 final 标记为

来更改它
static {
System.out.println(Test.x);
}

final static int x = 10;

代码现在将输出 10。您可以通过比较 javap -c Test.class 的非最终和最终字段情况的输出来看到它,字节码的顺序将反转:

6: invokevirtual #4                  // Method java/io/PrintStream.println:(I)V
9: bipush 10

在我看来,Java 编译器的前向引用错误似乎是解决 JVM 中静态初始化陷阱的一种解决方法。

关于java - 当静态变量处于 RIWO 状态时,是否可以直接访问它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51183788/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com