据说java中的静态 block 只在加载该类时运行一次。但这究竟意味着什么? JVM(Java Virtual Machine)在哪个点加载了一个类?
是在那个类中的main方法被调用的时候吗?并且是不是同一个类的所有父类(super class)在main方法开始执行的时候也都加载了?
考虑 A 扩展 B 和 B 扩展 C。它们都有静态 block 。如果 A 有 main 方法,那么静态 block 的执行顺序是什么?
最佳答案
这在 Execution 中有描述JLS 的部分。即:
Initialization of a class consists of executing its static initializers and the initializers for static fields declared in the class. Initialization of an interface consists of executing the initializers for fields declared in the interface.
Before a class is initialized, its direct superclass must be initialized, but interfaces implemented by the class need not be initialized. Similarly, the superinterfaces of an interface need not be initialized before the interface is initialized.
因此在您的示例中,“最顶层”类 (C
) 的静态 block 首先运行,然后是 B
的静态 block ,然后是派生程度最高的类。
有关加载类的所有步骤的详细说明,请参阅该文档。
(类在第一次被主动使用时加载。)
关于java - "When a Class is loaded"到底是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8550567/