First, compare the intermediate code generated by the two code segments:
Public class AppConfig {
Public static final boolean debug = true;
}
Public class DebugCode {
Public static void main (String [] args ){
If (AppConfig. debug ){
System. out. println ("Some debug information ");
}
}
}
DebugCode intermediate code (Part ):
Public class org. levin. insidejvm. miscs. DebugCode {
Public static void main (java. lang. String [] args );
0 getstatic java. lang. System. out: java. io. PrintStream [16]
3 ldc <String "Some debug information"> [22]
5 invokevirtual java. io. PrintStream. println (java. lang. String): void [24]
8 return
}
Public class AppConfig {
Public static final boolean debug = false;
}
Public class ReleaseCode {
Public static void main (String [] args ){
If (AppConfig. debug ){
System. out. println ("Some debug information ");
}
}
}
ReleaseCode intermediate code (Part ):
Public class org. levin. insidejvm. miscs. ReleaseCode {
Public static void main (java. lang. String [] args );
0 return
}
In the above Code, it is obvious that the code in DebugCode and ReleaseCode is the same, but AppConfig. the debug value is different, but different intermediate code is generated, that is, the compiler is in AppConfig. when debug is false, the statement in if is ignored. With this feature, we can implement Conditional compilation according to the configuration, so that different conditions can generate different intermediate code, not just different running results.
However, why is such a behavior?
This is because the compiler parses final modified variables of the basic type and String type into a local copy during compilation, in this way, the compiler will not execute the if statement that explicitly knows the ReleaseCode during compilation, so it can be optimized. The replacement result also enables the int variable modified with final to appear in the switch-case statement.
Defects of this method
The defect of this method lies in the fact that Conditional compilation of this mechanism is required, and AppConfig is being changed. when debugging values, you must compile the AppConfig class and ReleaseCode class at the same time (that is, you cannot compile only the AppConfig class ).