“什么时候”有很多很好的答案,比如在这个话题中——When does static class initialization happen?现在我的问题是“如何”。这是来自 Stephen C 的回答的引用
A classes static initialization normally happens immediately before the first time one of the following events occurs:
- 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 executed.
那么内部是如何完成的呢?每条可以触发初始化的指令都用 if
?任何工作 :-) 实现的细节对我来说都很好。
我用“Java”标记了这个问题,但如果我没记错的话,C# 和 Swift 也会按需初始化静态数据——一般来说——。
最佳答案
如评论中所述,这种事情可以通过段错误来完成,但对于 Java 这并不是真正必要的。
请记住,Java 字节码不是由机器直接执行的——在它被 JIT 编译成真正的机器指令之前,它会被解释和分析以确定何时编译它,这已经涉及为每个字节码指令执行大量的机器指令。这段时间检查静态初始化的所有条件是没有问题的。
字节码也可以编译成带有检查的机器码,在第一次执行检查后重写或修补。这种事情也会由于许多其他原因而发生,例如自动内联和转义分析,所以像这样进行静态初始化检查并不是什么大问题。
简而言之,有很多方法,但关键是当你运行一个 Java 程序时,除了你实际编写的代码之外,还有很多事情要做。
关于java - 静态数据是如何初始化的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34549118/