Java 中的静态/实例初始化程序块以什么顺序运行? [英] In what order do static/instance initializer blocks in Java run?
问题描述
假设一个项目包含多个类,每个类都有一个静态初始化块.这些块以什么顺序运行?我知道在一个类中,这些块按照它们在代码中出现的顺序运行.我读过它在各个类中都是相同的,但是我编写的一些示例代码不同意这一点.我使用了这个代码:
Say a project contains several classes, each of which has a static initializer block. In what order do those blocks run? I know that within a class, such blocks are run in the order they appear in the code. I've read that it's the same across classes, but some sample code I wrote disagrees with that. I used this code:
package pkg;
public class LoadTest {
public static void main(String[] args) {
System.out.println("START");
new Child();
System.out.println("END");
}
}
class Parent extends Grandparent {
// Instance init block
{
System.out.println("instance - parent");
}
// Constructor
public Parent() {
System.out.println("constructor - parent");
}
// Static init block
static {
System.out.println("static - parent");
}
}
class Grandparent {
// Static init block
static {
System.out.println("static - grandparent");
}
// Instance init block
{
System.out.println("instance - grandparent");
}
// Constructor
public Grandparent() {
System.out.println("constructor - grandparent");
}
}
class Child extends Parent {
// Constructor
public Child() {
System.out.println("constructor - child");
}
// Static init block
static {
System.out.println("static - child");
}
// Instance init block
{
System.out.println("instance - child");
}
}
并得到这个输出:
开始
静态 - 祖父母
静态 - 父
静态 - 子
实例 - 祖父母
构造函数 - 祖父母
实例 - 父
构造函数 - 父
实例 - 子
构造函数 - 子
结束
START
static - grandparent
static - parent
static - child
instance - grandparent
constructor - grandparent
instance - parent
constructor - parent
instance - child
constructor - child
END
显而易见的答案是,父母的块先于孩子的块运行,但这可能只是巧合,如果两个类不在同一层次结构中,则无济于事.
The obvious answer from that is that parents' blocks run before their children's, but that could just be a coincidence and doesn't help if two classes aren't in the same hierarchy.
我通过将其附加到 LoadTest.java 来修改我的示例代码:
I modified my example code by appending this to LoadTest.java:
class IAmAClassThatIsNeverUsed {
// Constructor
public IAmAClassThatIsNeverUsed() {
System.out.println("constructor - IAACTINU");
}
// Instance init block
{
System.out.println("instance - IAACTINU");
}
// Static init block
static {
System.out.println("static - IAACTINU");
}
}
正如类名所暗示的那样,我从未在任何地方引用过新类.新程序产生与旧程序相同的输出.
As implied by the class name, I never referenced the new class anywhere. The new program produced the same output as the old one.
推荐答案
类的静态初始值设定项在第一次访问类时运行,无论是为了创建实例,还是为了访问静态方法或字段.
The static initializer for a class gets run when the class is first accessed, either to create an instance, or to access a static method or field.
因此,对于多个类,这完全取决于为加载这些类而运行的代码.
So, for multiple classes, this totally depends on the code that's run to cause those classes to get loaded.
这篇关于Java 中的静态/实例初始化程序块以什么顺序运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!