在 main 方法之前执行静态块
Static block execution before main method
class 的静态块是否在相同 class 的主要方法之前执行?
示例:
public class Example {
static
{
System.out.println("hi");
}
public static void main(String[] args) {
System.out.println("bye");
}
}
这个程序的输出是:
hi
bye
我的疑问是为什么输出不是:
bye
在调用任何方法(或创建任何实例)之前,Java 将 运行 class 的静态初始化器。 JLS, Section 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.
部分初始化顺序为:
- Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.
因此,静态初始值设定项是运行先,打印"hi";然后调用 main
打印“再见”。
只有在 main() 中的任何内容之前执行静态块中的内容才有意义。如果您要定义 "static PI = 3.14157;" ,您不希望它在 main 方法中被知道吗?任何其他方式都会使目的落空。
事实证明,静态项目在加载时执行。
好的,当我在命令提示符下 运行 使用 -- java 示例的程序时,我得到了答案。在后台 java 命令执行主线程作为 -- example.main() -- 这类似于静态方法调用。
所以静态块中的语句比我的主要方法先执行。
class 的静态块是否在相同 class 的主要方法之前执行?
示例:
public class Example {
static
{
System.out.println("hi");
}
public static void main(String[] args) {
System.out.println("bye");
}
}
这个程序的输出是:
hi
bye
我的疑问是为什么输出不是:
bye
Java 将 运行 class 的静态初始化器。 JLS, Section 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.
部分初始化顺序为:
- Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.
因此,静态初始值设定项是运行先,打印"hi";然后调用 main
打印“再见”。
只有在 main() 中的任何内容之前执行静态块中的内容才有意义。如果您要定义 "static PI = 3.14157;" ,您不希望它在 main 方法中被知道吗?任何其他方式都会使目的落空。
事实证明,静态项目在加载时执行。
好的,当我在命令提示符下 运行 使用 -- java 示例的程序时,我得到了答案。在后台 java 命令执行主线程作为 -- example.main() -- 这类似于静态方法调用。 所以静态块中的语句比我的主要方法先执行。