Java中的静态块未执行 [英] Static block in Java not executed

查看:233
本文介绍了Java中的静态块未执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

推荐答案


  1. A static final int 字段是一个编译时常量,它的值被硬编码到目标类中,而不引用它的原点;

  2. 因此您的主类不会触发包含该字段的类的加载;

  3. 因此不会执行该类中的静态初始化程序。

  1. 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;
  2. therefore your main class does not trigger the loading of the class containing the field;
  3. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆