How to cancel compiler optimization of compilation constants when compiling java?
About compile-time constants:
See link below
I probably understand that perhaps the problem you are facing is that you want to recompile a java file (for example
A.java), there is a constant (such as
final int a) is different from the last compilation, but the other uses
AThe file (such as
javacAt the time of the last compilation, the
A.classThe constants inside are directly inlined, so they cannot achieve the desired effect.
If so, for
StringYou can use
.intern()To prevent the compiler from optimizing, for other types, you can either not define constants or define constants as
Private, and then use a
staticMethod to return this constant.
Editor: The host mentioned that the source file of the other party (I guess the constant provider) cannot be modified, so there is another way to force the content of the constant to be read, which is to use reflection.import java.lang.reflect.Field // Inside some method Field field = ConstProvider.class.getField("SOME_CONSTANT"); Object value = field.get(null);
If the type of constant is int, it can be used
getInt(null)Wait, wait, wait.
I have tested it and this method is completely available.