Java静态 block 引用另一个类中的静态变量

标签 java language-lawyer

public class A {
  public static String HOST;

  static {
    HOST = ...;
  }
}

public class B {
    public static String URL;

    static{
         URL = A.HOST + ...;
    }
}

我的问题是 A.HOST 是否会在 B 使用之前正确初始化? 此行为是否在规范中定义?

最佳答案

是的,行为定义明确 here .

简而言之,引用该链接

Initialization of a class or interface consists of executing the class or interface initialization method <clinit>

...

A class or interface may be initialized only as a result of:

The execution of any one of the Java Virtual Machine instructions new, getstatic, putstatic, or invokestatic that references the class or interface (§new, §getstatic, §putstatic, §invokestatic). All of these instructions reference a class directly or indirectly through either a field reference or a method reference.

Upon execution of a new instruction, the referenced class or interface is initialized if it has not been initialized already.

Upon execution of a getstatic, putstatic, or invokestatic instruction, the class or interface that declared the resolved field or method is initialized if it has not been initialized already.

The first invocation of a java.lang.invoke.MethodHandle instance which was the result of resolution of a method handle by the Java Virtual Machine (§5.4.3.5) and which has a kind of 2 (REF_getStatic), 4 (REF_putStatic), or 6 (REF_invokeStatic).

Invocation of certain reflective methods in the class library (§2.12), for example, in class Class or in package java.lang.reflect.

The initialization of one of its subclasses.

Its designation as the initial class at Java Virtual Machine start-up (§5.2).

<clinit> method 是初始化静态变量的方法(由编译器创建)并具有您放入 static 中的代码块

在你的例子中,当 static类 block B运行(这是 <clinit> 会做的),它将有一个 getStatic操作码,请求 A.HOST .所以A的初始化将被触发,并且A.HOST初始化。所以你会读到正确的值。

关于Java静态 block 引用另一个类中的静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31428457/

相关文章:

java - 更改文本字段的值,因为另一个文本字段的值已更改,并且相同但相反,导致错误

java - 如何根据用户输入自动创建复选框

java - Mongodb,仅查找所有最新的映射记录

c++ - POD 类型的二进制 I/O 如何不破坏别名规则?

c++ - 在编译时常量中为字符串文字添加下标

c++ - 为什么这个编译成功?

C++ 复制构造函数中的命名空间冲突

java - 如何实现具有最大高度和内部滚动的多行 TextView

java - 为什么 spring boot 会生成扩展名为 .original 的 jar 或 war 文件?

c++ - std::vector 是否可以简单复制,为什么?