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/