Java Virtual Machine compilation mechanism: Changing the constants Section
Recently a Java project needs to modify the value of a static constant, the local modification after compiling the normal debugging, and then the corresponding entity class file upload to the server corresponding directory after the system still do its own, various clear cache, various restarts, and finally query the relevant information, Use the GUI anti-compilation tool to Decompile and view the compiled source, and finally find the problem:
It is useless to simply modify static variables, and to recompile all classes that reference static variables, otherwise it will not take effect.
This involves the Java Virtual Machine compilation mechanism: In a Java file, a static constant that points to the build static final will be resolved at run time to a local constant value (that is, the static constant is compiled and becomes a constant, not the original code). This applies to all underlying data types (like int, float, etc.) and java.lang.String.
For example:
public class Contant{public static final String STR = "alexgaoyh";//...... }
These constants are then used in some logical sections of code. This makes it easy to manage constants, avoids a lot of magic number/text, and changes the constant content simply by changing the class.
publi C class testservice {public void Span class= "Hljs-title" >dosome (/ /This applies the static constant contant.strsystem of the previous class. out.println (CONTANT.STR);} }
Class Testservice uses the constant CONTANT.STR, which is the value obtained by the Contant class on the surface, and in fact, after Testservice is compiled, its code has changed to
public class TestService {public void doSome() {//这里把静态常量Contant.STR直接编译成为了一个常量"alexgaoyh"System.out.println("alexgaoyh");}}
This means that in all places where constants are used, they must be re-compiled to take effect.
Java constants are not re-fetched after initialization