什么时候进行静态类初始化? [英] When does static class initialization happen?

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

问题描述

何时初始化静态字段?如果我从不实例化一个类,但是我访问一个静态字段,是否所有静态块和私有静态方法用于实例化那个时刻调用的私有静态字段(按顺序)?

When are static fields initialized? If I never instantiate a class, but I access a static field, are ALL the static blocks and private static methods used to instantiate private static fields called (in order) at that instant?

如果我调用静态方法怎么办?它是否也运行所有静态块?在方法之前?

What if I call a static method? Does it also run all the static blocks? Before the method?

推荐答案

类的静态初始化通常在第一次发生以下事件之前发生:

A class's static initialization normally happens immediately before the first time one of the following events occur:


  • 创建了一个类的实例,

  • 调用类的静态方法,

  • 分配了类的静态字段,

  • 使用非常量静态字段,或

  • < strike>对于顶级类,执行词法嵌套在类中的断言语句 1

  • an instance of the class is created,
  • a static method of the class is invoked,
  • a static field of the class is assigned,
  • a non-constant static field is used, or
  • for a top-level class, an assert statement lexically nested within the class is executed1.

请参阅 JLS 12.4.1

也可以使用 Class。 forName(fqn,true,classLoader) 或简短形式 Class.forName(fqn)

It is also possible to force a class to initialize (if it hasn't already initialized) by using Class.forName(fqn, true, classLoader) or the short form Class.forName(fqn)

1 - 最终要点出现在JLS for Java 6到Java 8中,但在规范中显然是错误的。它最终在Java 9 JLS中得到了纠正:请参阅来源

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

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