I have a situation where I have few files having final static String variables (constants). Now these variables are used in many files using the classname.variable. These files are present in different jars. First jar contains the constants, second jar will contain the files that are using the constants. It is understood that when java compilation happens for the files which are using the constants, classname.variable will be replaced by the constant itself during compilation.
Now, suppose I change the value of a constant and build the first jar, there will not be any compilation issue nor runtime issue in the application. But in the second jar, previous constant will be there in the class file. How do I avoid this? Please provide suggestions. I'm building jars using ANT.
The value copying behavior only applies to compile-time constants. A variable is a compile-time constant if it is declared final and initialized with a compile-time constant. Therefore you can enforce a variable to be no compile-time constant by not initializing it:
public static final String CONSTANT_BUT_NOT_COMPILE_TIME_CONSTANT;
static {
CONSTANT_BUT_NOT_COMPILE_TIME_CONSTANT = "the value being constant at runtime";
}
Here, the variable is not initialized with the constant value but assigned after the declaration. Therefore it is not a compile-time constant and thus, it’s value never copied at compile time. It is still immutable at runtime.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With