静态块未被调用 [英] Static block is not being called

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

问题描述

谁可以解释发生了什么?

Who can explain what's going on?

public class MagicFinal {

    public static void main(String[] args) {
        System.out.println(A.s);
    }
}

class A {
    static {
        System.out.println("class has been loaded");
    }

    public static final String s = "final";

    public static final Integer i = 3;


}

控制台:


final

final

这是什么?我不明白为什么没有加载类,我知道类总是在第一次调用时加载。字段 s 在字符串池中,我看到最终修饰符是魔术。

What's it? I don't understand why the class has not been loaded, I know classes always load at the first call. Field s is in pool of string, I see that final modifier is magic.

如果我删除final修饰符( public static String s =final)我会得到

If I delete final modifier (public static String s = "final" ) I will get

控制台:


已加载课程

class has been loaded

final

注意:我更改了字段 i public static final int i = 3; 并在控制台中显示它。
我和String情况一样。为什么?

Note: I have changed field i : public static final int i = 3; and show it in console. I got the same as in String situation. Why?

推荐答案

final是一个字符串文字因此是 编译 - 时间常数表达式 。使用编译时常量表达式初始化的静态最终变量的值直接硬编码到引用它的类中,并且不对引发类进行引用。因此,不会发生原始类的初始化。

"final" is a string literal and as such is a compile-time constant expression. The value of a static final variable initialized with a compile-time constant expression is directly hardcoded into the class which references it, and no reference is made to the originating class. Therefore the initialization of the originating class does not occur.

作为一个侧面,请注意类加载和类之间的区别初始化:只有后者的出现由JLS精确指定。类加载可以随时发生。

As a side point, please note the distinction between class loading and class initialization: only the latter's occurrence is precisely specified by the JLS. Class loading can happen at any time.

这篇关于静态块未被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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