问题描述
这是从有效的Java:
This is from Effective Java :
// Implementing a fromString method on an enum type
private static final Map<String, Operation> stringToEnum
= new HashMap<String, Operation>();
static { // Initialize map from constant name to enum constant
for (Operation op : values())
stringToEnum.put(op.toString(), op);
}
// Returns Operation for string, or null if string is invalid
public static Operation fromString(String symbol) {
return stringToEnum.get(symbol);
}
我的问题是关于这一行:
My question is regarding the line :
我以为静态块在构造函数运行之前被执行。实际上是在类加载时执行的。
I thought the static block gets executed before the constructor runs. The are actually executed during class load time.
我在这里缺少什么?
推荐答案
作为:为什么有一个保证枚举常量将在静态块运行之前被初始化。答案在中给出,而具体示例在中给出,其中以下解释:
I understand your question as: why is there a guarantee that the enum constants will be initialised before the static block is run. The answer is given in the JLS, and a specific example is given in #8.9.2.1, with the following explanation:
和枚举常量是隐式的最终静态,并在静态初始化程序块之前声明。
and the enums constants are implicitly final static and are declared before the static initializer block.
编辑
行为与普通类没有什么不同。下面的代码打印:
The behaviour is not different from a normal class. The code below prints:
In constructor: PLUS
PLUS == null MINUS == null
In constructor: MINUS
PLUS != null MINUS == null
In static initialiser
PLUS != null MINUS != null
In constructor: after static
PLUS != null MINUS != null
public class Operation {
private final static Operation PLUS = new Operation("PLUS");
private final static Operation MINUS = new Operation("MINUS");
static {
System.out.println("In static initialiser");
System.out.print("PLUS = " + PLUS);
System.out.println("\tMINUS = " + MINUS);
}
public Operation(String s) {
System.out.println("In constructor: " + s);
System.out.print("PLUS = " + PLUS);
System.out.println("\tMINUS = " + MINUS);
}
public static void main(String[] args) {
Operation afterStatic = new Operation ("after static");
}
}
这篇关于枚举类型w.r.t中的静态块的执行顺序到构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!