为什么我的静态代码块不执行? [英] Why doesn't my static block of code execute?
问题描述
我正在尝试运行此代码,但我发现了final的这种行为与静态:代码运行时没有执行A的静态块。请提供原因。
I am trying to run this code, I but found out this behavior of final with static: the code runs without executing static block of A. Please provide me with the reason.
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类的静态块不运行?
Why doesn't the static block of Class A run?
推荐答案
问题是 Aa
是常量变量。
原始类型或类型String的变量,是最终的并使用编译时常量表达式(第15.28节)初始化,称为常量变量。
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
方法已完全编译 好像它是:
Therefore your Manager.main
method is compiled exactly as if it were:
public static void main(String ...arg) {
System.out.println("main");
System.out.println(9);
}
没有真正的参考 Aa
以上,所以 A
类甚至不需要存在,更不用说初始化了。 (您可以删除 A.class
并仍然运行经理
。)
There's no real reference to A.a
any more, so the A
class doesn't even need to exist, let alone be initialized. (You can delete A.class
and still run Manager
.)
如果您依赖于使用 Aa
来确保类型已初始化,则不应添加no-op方法:
If you're relying on using A.a
to make sure the type is initialized, you shouldn't add a no-op method instead:
public static void ensureClassIsInitialized() {
}
然后从 main
方法中调用 。尽管如此,这是非常不寻常的。
then just call that from your main
method. It's very unusual to need to do this though.
这篇关于为什么我的静态代码块不执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!