java - 静态类什么时候初始化?

标签 java import initialization static-import

考虑一个 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() 时?

最佳答案

对象 o1o2 在您的 static 上下文中不可用,除非它们也成为 static

JVMS指出

Any static initializers declared in a class are executed when the class is initialized

Further

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/

相关文章:

java - 我如何确认 _JAVA_OPTS 正在执行?

java - 如何通过jdbc将数据从数据流加载到postgresql中

delphi - 如何解决 Delphi 包中隐式导入的单元

python - 只计算一次python变量

c++ - 用花括号 C++ 实例化一个对象

java - 如何将 DateTimeFormatter 包含到项目中

java - 限制CPU使用的线程数

java - 导入文件夹中更上方的 Java 类

hibernate - org.hibernate.LazyInitializationException : could not initialize proxy - the owning Session was closed

c++ - 类模板静态成员初始化两次