The ultimate static string compilation problem. Any suggestions how to avoid?

I have a situation where I have few files with final static String variables (constants). Now these variables are used in many files using classname.variable. These files are present in different banks. The first bank contains constants, the second bank will contain files that use constants. It is clear that when compiling java for files that use constants, classname.variable will be replaced by the constant itself at compile time.

Now, suppose I change the value of the constant and build the first jar, there will be no compilation or execution issue in the application. But in the second jar, the previous constant will be there in the class file. How can I avoid this? Please provide suggestions. I am creating jars using ANT.

+3


source to share


2 answers


The copy-value behavior applies only to compile-time constants. Variable - a compile-time constants if it is declared final

and initialized to compile-time constant. Therefore, you can force the variable so that it is not a compile-time constant without 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 hence its value is never copied at compile-time. It is still unchanged at runtime.

+2


source


Just remove the last modifier. Or don't forget to rebuild the second can.



0


source







All Articles