How to cancel compiler optimization of compilation constants when compiling java?

  java, question

How to cancel compiler optimization of compilation constants when compiling java?

About compile-time constants:

See link below
http://stackoverflow.com/questions/90 …

I probably understand that perhaps the problem you are facing is that you want to recompile a java file (for exampleA.java), there is a constant (such asfinal int a) is different from the last compilation, but the other usesA.classTheAThe file (such asB.javaDue tojavacAt the time of the last compilation, theA.classThe constants inside are directly inlined, so they cannot achieve the desired effect.

If so, forStringYou can use.intern()To prevent the compiler from optimizing, for other types, you can either not define constants or define constants asPrivate, and then use astaticMethod to return this constant.

Source:
http://stackoverflow.com/questions/37 …
http://docs.oracle.com/javase/specs/j …

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 usedgetInt(null)Wait, wait, wait.
I have tested it and this method is completely available.