静态类初始化何时发生? [英] When does static class initialization happen?

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

问题描述

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

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:

  • 创建了一个类的实例,
  • 调用类的静态方法,
  • 分配了类的静态字段,
  • 使用了非常量的静态字段,或者
  • 对于顶级类,执行词法嵌套在类中的 assert 语句1.

请参阅 JLS 12.4.1.

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

1 - 最后一个要点出现在 Java 6 到 Java 8 的 JLS 中,但这显然是规范中的一个错误.它最终在 Java 9 JLS 中得到纠正:参见 source.

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

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