编译时在代码中替换 Java 静态最终值? [英] Java static final values replaced in code when compiling?

查看:27
本文介绍了编译时在代码中替换 Java 静态最终值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在java中,假设我有以下内容

In java, say I have the following

==fileA.java==
class A
{  
    public static final int SIZE = 100;
}  

然后在另一个文件中我使用这个值

Then in another file I use this value

==fileB.java==  
import A;
class b
{
      Object[] temp = new Object[A.SIZE];
}

当它被编译时 SIZE 被替换为值 100,所以如果我要替换 FileA.jar 而不是 FileB.jar,对象数组会得到新值还是会它已被硬编码为 100,因为这是最初构建时的值?

When this gets compiled does SIZE get replaced with the value 100, so that if I were to replace the FileA.jar but not FileB.jar, would the object array get the new value or would it have been hardcoded to 100 because that's the value when it was originally built?

推荐答案

是的,Java 编译器确实将示例中的 SIZE 等静态常量值替换为它们的字面值.

Yes, the Java compiler does replace static constant values like SIZE in your example with their literal values.

因此,如果您稍后在 A 类中更改 SIZE 但不重新编译 b 类,您仍然会看到旧的b 类中的值.您可以轻松地对此进行测试:

So, if you would later change SIZE in class A but you don't recompile class b, you will still see the old value in class b. You can easily test this out:

文件 A.java

public class A {
    public static final int VALUE = 200;
}

文件 B.java

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

编译 A.java 和 B.java.现在运行:java B

Compile A.java and B.java. Now run: java B

更改 A.java 中的值.重新编译 A.java,而不是 B.java.再次运行,您将看到打印的旧值.

Change the value in A.java. Recompile A.java, but not B.java. Run again, and you'll see the old value being printed.

这篇关于编译时在代码中替换 Java 静态最终值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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