class 的 JVM 初始化顺序是什么,它有另一个 class 的实例
What is the JVM initialization order for a class has an instance of another class
假设 JVM 第一次加载了以下 Foo
class 并且它刚刚传递到链接步骤(在解析期间)。
public static void main(...) {
new Foo();
}
public class Foo {
private static int a = 4;
private static Hoo hoo = new Hoo();
Foo (){
Log.i("Test", ">> Test foo's created!");
}
}
public class Hoo {
private static int b = 4;
private static Soo soo = new Soo();
Hoo (){
Log.i("Test", ">> Test hoo's created!");
}
}
public class Soo {
private static int b = 4;
private static Koo soo = new Koo();
Soo (){
Log.i("Test", ">> Test soo's created!");
}
}
...
现在我的问题是这个。我们知道,在完成 child class 构造之前,系统会递归调用 base/super class 构造函数。上面的代码中是否存在类似的逻辑?我的意思是 JVM 会在完成 Hoo()
和 Soo()
构造之后立即完成 Foo
的构造吗?
谢谢。
I mean does JVM will complete the construction of Foo right after completing the Hoo() and Soo() construction ?
基本上……是的。
根据JLS 12.4.1:
A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
T is a class and an instance of T is created.
A static method declared by T is invoked.
A static field declared by T is assigned.
A static field declared by T is used and the field is not a constant variable (§4.12.4).
T is a top level class (§7.6) and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.
等等。
在您的示例中,这意味着 类 将按照 Koo
、Soo
、Hoo
、Foo
的顺序进行初始化,并且在 main
方法中执行 new Foo()
表达式将触发它。
如果不同 类 的静态初始化之间存在循环依赖,事情会变得有点复杂(和讨厌),但 JLS 也涵盖了这种边缘情况。
假设 JVM 第一次加载了以下 Foo
class 并且它刚刚传递到链接步骤(在解析期间)。
public static void main(...) {
new Foo();
}
public class Foo {
private static int a = 4;
private static Hoo hoo = new Hoo();
Foo (){
Log.i("Test", ">> Test foo's created!");
}
}
public class Hoo {
private static int b = 4;
private static Soo soo = new Soo();
Hoo (){
Log.i("Test", ">> Test hoo's created!");
}
}
public class Soo {
private static int b = 4;
private static Koo soo = new Koo();
Soo (){
Log.i("Test", ">> Test soo's created!");
}
}
...
现在我的问题是这个。我们知道,在完成 child class 构造之前,系统会递归调用 base/super class 构造函数。上面的代码中是否存在类似的逻辑?我的意思是 JVM 会在完成 Hoo()
和 Soo()
构造之后立即完成 Foo
的构造吗?
谢谢。
I mean does JVM will complete the construction of Foo right after completing the Hoo() and Soo() construction ?
基本上……是的。
根据JLS 12.4.1:
A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
T is a class and an instance of T is created.
A static method declared by T is invoked.
A static field declared by T is assigned.
A static field declared by T is used and the field is not a constant variable (§4.12.4).
T is a top level class (§7.6) and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.
等等。
在您的示例中,这意味着 类 将按照 Koo
、Soo
、Hoo
、Foo
的顺序进行初始化,并且在 main
方法中执行 new Foo()
表达式将触发它。
如果不同 类 的静态初始化之间存在循环依赖,事情会变得有点复杂(和讨厌),但 JLS 也涵盖了这种边缘情况。