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也会按需初始化静态数据(通常).
解决方法:
正如评论中提到的那样,可以通过segfaults来完成这种事情,但是对于Java而言,这并不是必须的.
请记住,Java字节码不是由机器直接执行的-在将JIT编译成真实的机器指令之前,先对其进行解释和分析以确定何时编译它,这已经涉及到每个字节码执行很多机器指令.指令.在这段时间内检查静态初始化的所有条件都没问题.
字节码也可以与检查一起编译成机器代码,在第一次执行检查后将其重写或打补丁.这种事情也可能由于其他许多原因而发生,例如自动内联和转义分析,因此像这样进行静态初始化检查不是什么大问题.
简而言之,有很多方法,但是关键是当您运行Java程序时,除了实际编写的代码外,还有很多其他事情在进行.
标签:static,java
来源: https://codeday.me/bug/20191119/2034543.html