Java中的静态块未执行 [英] Static block in Java not executed
问题描述
class Test{
public static void main(String arg[]){
System.out.println("**MAIN METHOD");
System.out.println(Mno.VAL);//SOP(9090);
System.out.println(Mno.VAL+100);//SOP(9190);
}
}
class Mno{
final static int VAL=9090;
static{
System.out.println("**STATIC BLOCK OF Mno\t:"+VAL);
}
}
我知道静态
加载类时执行的块。但在这种情况下,类 Mno
中的实例变量是 final
,因为 static
块未执行。
I know that a static
block executed when class loaded. But in this case the instance variable inside class Mno
is final
, because of that the static
block is not executing.
为什么会这样?如果我删除 final
,它会正常工作吗?
Why is that so? And if I would remove the final
, would it work fine?
首先分配哪个内存,静态最终
变量或 static
阻止?
Which memory will be allocated first, the static final
variable or the static
block?
如果由于 final
访问修饰符而没有加载类,那么变量如何获取内存?
If due to the final
access modifier the class does not get loaded, then how can the variable get memory?
推荐答案
- A
static final int
字段是一个编译时常量,它的值被硬编码到目标类中,而不引用它的原点; - 因此您的主类不会触发包含该字段的类的加载;
- 因此不会执行该类中的静态初始化程序。
- A
static final int
field is a compile-time constant and its value is hardcoded into the destination class without a reference to its origin; - therefore your main class does not trigger the loading of the class containing the field;
- therefore the static initializer in that class is not executed.
具体细节,编译的字节码对应于:
In specific detail, the compiled bytecode corresponds to this:
public static void main(String arg[]){
System.out.println("**MAIN METHOD");
System.out.println(9090)
System.out.println(9190)
}
一旦删除 final
,它就不再是编译时常量,并且上述特殊行为不适用。 Mno
类按预期加载,并执行静态初始化程序。
As soon as you remove final
, it is no longer a compile-time constant and the special behavior described above does not apply. The Mno
class is loaded as you expect and its static initializer executes.
这篇关于Java中的静态块未执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!