静态类什么时候初始化?

发布于 2025-01-07 02:46:30 字数 791 浏览 0 评论 0原文

考虑 仅包含静态字段的 Java 类并且没有构造函数:

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 OnlyStatic.compute
int a = OnlyStatic.compute(3);

或者直接使用,假设调用者位于同一个包中:

int a = OnlyStatic.compute(3);

o1 和o2 初始化了吗?在导入时,还是在第一次调用 compute() 时?

Consider a Java class with static fields only and no constructor:

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;
   }
}

In a different class, the method compute is used, either by static import:

static import OnlyStatic.compute
int a = OnlyStatic.compute(3);

Or directly, assuming the caller is in the same package:

int a = OnlyStatic.compute(3);

When are o1 and o2 initialized? At the import, or when compute() is called for the first time?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

南冥有猫 2025-01-14 02:46:30

如果不将对象 o1o2 设为 static,它们也无法在您的 static 上下文中使用。

JVMS 指出

类中声明的任何静态初始化器都会在类初始化时执行

进一步

类或接口类型T将在第一次出现以下任何一项之前立即初始化:

  • T 是一个类,并且创建了 T 的实例。
  • T 是一个类,并且调用 T 声明的静态方法。
  • 分配了 T 声明的静态字段。
  • 使用了 T 声明的静态字段,并且该字段不是常量变量(第 4.12.4 节)。
  • T 是一个顶级类,并且词法嵌套在 T 中的断言语句 (§14.10) 是
    被处决。

因此,在您的情况下,当首先执行静态方法compute()时。

The objects o1 and o2 are not available to your static context without making them static also.

JVMS states that

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.

So in your case, when the static method compute() is first executed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文