Java静态最终值在编译时在代码中替换

Java静态最终值在编译时在代码中替换

本文介绍了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 down the road 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 thats the value when it was originally built?

推荐答案

感谢

Stephanie

解决方案

是的,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静态最终值在编译时在代码中替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 16:57