“加载类时”是什么意思?实际上是什么意思?
据说java中的静态块仅在加载该类时运行一次。但这实际上意味着什么呢?类在什么时候被 JVM(Java 虚拟机)加载?
是在调用该类中的 main 方法时吗?而且是不是在main方法开始执行的时候,同一个类的所有超类也都被加载了呢?
考虑 A 扩展 B 和 B 扩展 C。它们都有静态块。如果A有main方法,那么静态块的执行顺序是什么?
It is said that static blocks in java run only once when that class is loaded. But what does it actually mean? At which point is a class loaded by JVM (Java Virtual Machine)?
Is it when the main method in that class is called? And is it that all the super-classes of the same class are also loaded when the main method starts execution?
Consider that A extends B and B extends C. All have static blocks. If A has the main method, then what will be the sequence of execution of static blocks?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(3)
我认为下面的示例将解决您的所有问题:
在初始化类之前,如果先前尚未初始化其超类,则对其超类进行初始化。
因此,测试程序:
class Super {
static { System.out.print("Super "); }
}
class One {
static { System.out.print("One "); }
}
class Two extends Super {
static { System.out.print("Two "); }
}
class Test {
public static void main(String[] args) {
One o = null;
Two t = new Two();
System.out.println((Object)o == (Object)t);
}
}
打印:
Super Two false
类 One 从未被初始化,因为它没有被主动使用,因此从未被链接到。类 Two 仅在其超类 Super 初始化后才初始化。
有关更多详细信息,请访问此链接
编辑详细信息:删除令人困惑的内容线。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
这在执行部分中进行了描述JLS。即:
因此,在您的示例中,“最顶层”类 (
C
) 的静态块首先运行,然后是B
的静态块,然后是最派生的类。有关加载类的所有步骤的详细说明,请参阅该文档。
(类在第一次被使用时被加载。)
This is described in the Execution section of the JLS. Namely:
So in your example, the static block of the "topmost" class (
C
) runs first, then that ofB
, then the most-derived one.See that documentation for a detailed description of all the steps that go into loading a class.
(Classes get loaded when they are first actively used.)