Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

Java static final values replaced in code when compiling?

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];
}

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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:

file A.java

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

file B.java

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...