考虑这样一个问题,我有如下两个 Java 文件:
// Dog.java
public class Dog {
public static final int count = 100;
}
// Pet.java
public class Pet {
public static final int dogCount = Dog.count;
}
这两个文件分别包含在两个不同的 jar 包中。如果我将 Dog.count
的值改为 200 并单独重新编译 dog.jar 文件(保持 pet.jar 文件不变),此时,Pet.dogCount
的值是多少?
答案是: Pet.dogCount
的值仍然为 100。
在 Java Spec 中有这样一段描述:
Note: If a primitive type or a string is defined as a constant and the value is known at compile time, the compiler replaces the constant name everywhere in the code with its value. This is called a compile-time constant. If the value of the constant in the outside world changes (for example, if it is legislated that pi actually should be 3.975), you will need to recompile any classes that use this constant to get the current value.
从中我们得知,代码中所有引用了编译时常量的地方都会在编译期间被替换成该常量的值。每当常量的值发生了变化,我们需要重新编译所有引用了该常量的类文件,以确保它们所使用的值是最新的。