为什么引用静态final字段不会触发类加载? [英] Why reference to a static final field will not trigger class loading?

查看:1030
本文介绍了为什么引用静态final字段不会触发类加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的测试代码:

I have a testing code like this:

public class Constants {
public static String c1 = "C1";

static {
    System.out.println("Constants Class Loaded!");
}
}

public class Test {
    public static void main(String[] args) {
        String c1 = Constants.c1;
        System.out.println(c1);
    }
}

其输出为:

Constants Class Loaded!
C1

因此,类常量由JVM加载。
但是如果我在类常量中的静态字段中添加一个final关键字:

So, the class Constants is loaded by JVM. But if I add a final keyword to the static field in class Constants:

public class Constants {
public static final String c1 = "C1";

static {
    System.out.println("Constants Class Loaded!");
}
}

其输出更改为:

C1

似乎未加载类常量。

我的本​​地环境是:

OS: Win7 x64
JVM: JRockit (build R28.2.0-79-146777-1.6.0_29-20111005-1808-windows-ia32, compiled mode)

所以,我的问题是:


  • 为什么要参考静态最终版字段不会触发类加载? JVM在满足此代码时会做什么(字节码)?

  • 这种行为是否取决于特定的JVM?或者这是Java语言规范中的规则?

  • 有什么优势&这个缺点?

谢谢。

推荐答案


为什么引用静态final字段不会触发类加载?
符合此代码时JVM会做什么(字节码)?

Why reference to a static final field will not trigger class loading? What will JVM do(bytecode) when it meets this code?

JLS说


类或接口类型T将在
首次出现以下任何一项之前立即初始化:

A class or interface type T will be initialized immediately before the first occurrence of any one of the following:


  • [...]

  • 使用由T声明的静态字段,该字段不是常量变量(§4.12.4)。

A 常量变量定义为


常量变量是原始类型的 final 变量或初始化的类型
String 使用常量表达式(§15.28)。

A constant variable is a final variable of primitive type or type String that is initialized with a constant expression (§15.28).

所以你的字段是这样一个常量变量iable和访问它不会导致类型被初始化。

So your field is such a constant variable and accessing it won't cause the type to be initialized.


这种行为取决于特定的JVM吗?或者这是Java
语言规范中的规则?

Is this behavior depending on specific JVM? Or this is a rule in Java language specification?

Java语言规范指定了这种行为。

The Java Language Specification specifies this behavior.


有什么好处&这个缺点?

What's the advantage & disadvantage of this?

缺点是它可能造成的混乱(如果你不知道Java语言规范的细节) 。

The disadvantage is the confusion it might cause (if you don't know the details of the Java Language specification).

优点是引用常量不会导致任何不必要的代码执行。

The advantage is that referring to constants doesn't cause any unnecessary execution of code.

这篇关于为什么引用静态final字段不会触发类加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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