考虑一个 Java class with static fields only并且没有构造函数:
public class OnlyStatic {
static O1 o1 = new o1();
static O2 o2 = new o2();
public static int compute(int whatever) {
return o1.foo+o2.bar+whatever;
}
}
在另一个类中,compute
方法被使用,或者通过static import
:
static import OnlyStatic.compute
int a = OnlyStatic.compute(3);
或者直接假设调用者在同一个包中:
int a = OnlyStatic.compute(3);
o1 和 o2 什么时候初始化?在导入时,还是第一次调用 compute()
时?
最佳答案
对象 o1
和 o2
在您的 static
上下文中不可用,除非它们也成为 static
。
JVMS指出
Any static initializers declared in a class are executed when the class is initialized
A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
- T is a class and an instance of T is created.
- T is a class and a static method declared by T is invoked.
- A static field declared by T is assigned.
- A static field declared by T is used and the field is not a constant variable (§4.12.4).
- T is a top-level class, and an assert statement (§14.10) lexically nested within T is executed.
所以在您的情况下,当静态方法 compute()
第一次执行时。
关于java - 静态类什么时候初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9361528/