我正在尝试运行这段代码,但我发现了 final with static 的这种行为:代码运行时没有执行 A 的静态 block 。请提供原因。
class A {
final static int a=9;
static { //this block is not executing ??
System.out.println("static block of A");
}
}
class Manager {
static {
System.out.println("manager sib");
}
public static void main(String ...arg) {
System.out.println("main");
System.out.println(A.a);
}
}
为什么A类静态 block 不运行?
最佳答案
问题是 A.a
是 constant variable .
A variable of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28), is called a constant variable.
因此你的 Manager.main
方法被编译完全就好像它是:
public static void main(String ...arg) {
System.out.println("main");
System.out.println(9);
}
不再有对 A.a
的真正引用,因此 A
类甚至不需要存在,更不用说初始化了。 (您可以删除 A.class
并仍然运行 Manager
。)
如果您依赖于使用 A.a
来确保类型已初始化,则不应添加无操作方法:
public static void ensureClassIsInitialized() {
}
然后只需从您的main
方法中调用that。不过,需要这样做是非常不寻常的。
关于java - 为什么我的静态代码块不执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15509337/