静态类何时会初始化? [英] When will a static class initialize?

查看:80
本文介绍了静态类何时会初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个具有以下内容的Java类静态字段,没有构造函数:

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

在另一个类中,通过 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);

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

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

推荐答案

对象 o1 o2 对您的 static 上下文不可用而不使它们也变为 static .

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

JVMS 指出

在类中声明的任何静态初始值设定项都在初始化类时执行

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

进一步

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

A class or interface type T will be initialized immediately before the first occurrence of any one of the following:

  • T 是一个类,并创建 T 的实例.
  • T 是一个类,并调用 T 声明的静态方法.
  • 分配了由 T 声明的静态字段.
  • 使用了 T 声明的静态字段,该字段不是常量变量(第4.12.4节).
  • T 是一个顶级类,并且以词法嵌套在 T 中的assert语句(第14.10节)是被执行.
  • 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().

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

这篇关于静态类何时会初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆