3

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.

NaveenBharadwaj
  • 1,212
  • 5
  • 19
  • 42
  • @RobbyCornelissen, I heard this from my Senior manager at work and this issue seems to be creating lot of problem. He wanted me to analyze this and find a solution. Correct me if I'm wrong. – NaveenBharadwaj Oct 21 '14 at 10:09
  • 4
    Seems that you're right. It surprised me. Anyway, solution can be found [here](http://stackoverflow.com/questions/377819/are-all-compile-time-constants-inlined). – Robby Cornelissen Oct 21 '14 at 10:10
  • try to use "volatile final static String", then java will inforce the use of the newest value – Riadh Oct 21 '14 at 10:12

2 Answers2

3

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.

Holger
  • 285,553
  • 42
  • 434
  • 765
0

Just remove the final modifier. Or make sure to rebuild the second jar.

sanigo
  • 625
  • 4
  • 14