Java Enum 为什么静态行只执行一次?
Java Enum why static line executes only once?
结果是:
1
3
1
3
1
3
2
构造函数为 A、B 和 C 运行(3 次)。但是,如果您使用 static 关键字,它只会运行一次。这是什么原因呢?为什么这一行最后执行?
enum Enums {
A, B, C;
{
System.out.println(1);
}
static {
System.out.println(2);
}
private Enums() {
System.out.println(3);
}
}
public class MainClass{
public static void main(String[] args) {
Enum en = Enums.C;
}
}
这里涉及三个不同的方面:
private Enums()
{
System.out.println(3);
}
这是构造函数。它(或其他一些潜在的构造函数)运行在创建实例时出现。
{
System.out.println(1);
}
这是一个实例初始化程序。 运行在构造对象时,无论使用哪个构造函数。
static
{
System.out.println(2);
}
这是一个静态初始化程序。一旦这个 class 被加载到 JVM 中,它就会得到 运行,无论是否正在创建一个实例。然而,由于我们正在处理一个枚举,它的所有实例都必须作为加载 class 的一部分创建。这就是为什么它 运行 在三个构造函数和初始值设定项之后。
要补充@smallhacker 的答案,您应该阅读 Static initializer in Java
中的答案
Uff! what is static initializer?
The static initializer is a static {} block of code inside java class,
and run only one time before the constructor or main method is called.
结果是:
1
3
1
3
1
3
2
构造函数为 A、B 和 C 运行(3 次)。但是,如果您使用 static 关键字,它只会运行一次。这是什么原因呢?为什么这一行最后执行?
enum Enums {
A, B, C;
{
System.out.println(1);
}
static {
System.out.println(2);
}
private Enums() {
System.out.println(3);
}
}
public class MainClass{
public static void main(String[] args) {
Enum en = Enums.C;
}
}
这里涉及三个不同的方面:
private Enums()
{
System.out.println(3);
}
这是构造函数。它(或其他一些潜在的构造函数)运行在创建实例时出现。
{
System.out.println(1);
}
这是一个实例初始化程序。 运行在构造对象时,无论使用哪个构造函数。
static
{
System.out.println(2);
}
这是一个静态初始化程序。一旦这个 class 被加载到 JVM 中,它就会得到 运行,无论是否正在创建一个实例。然而,由于我们正在处理一个枚举,它的所有实例都必须作为加载 class 的一部分创建。这就是为什么它 运行 在三个构造函数和初始值设定项之后。
要补充@smallhacker 的答案,您应该阅读 Static initializer in Java
中的答案Uff! what is static initializer?
The static initializer is a static {} block of code inside java class, and run only one time before the constructor or main method is called.