Conditional compilation is definitely a good thing. For example, in C or CPP, conditional compilation can be accomplished by preprocessing statements. But in Java there is no preprocessing, macros define these things, and sometimes in some projects, we need conditional compilation. So, in Java, how do you implement conditional compilation?
Conditional compilation is definitely a good thing. For example, in C or CPP, conditional compilation can be accomplished by preprocessing statements. The code is as follows:
#IFDEF Debug #UNDEF debug #ENDIF #define DEBUG #IFDEF debuug /* code block 1 * / #ELSE/* code block 2*/
But in Java there is no preprocessing, macros define these things, and sometimes in some projects, we need conditional compilation. So, in Java, how do you implement conditional compilation?
Let's look at an example.
Write a HelloWorld program. The code is as follows:
Public class Hello { publicstaticvoid main (string[] args) { System.out.println ( "Hello, world!." );
Save as Hello.java and compile, get a class file, and observe that the file size is 417 bytes. Then we decompile the file and use the Jd-gui. Get the code as follows:
Importpublicclass Hello { publicstaticvoid Main (string[] paramarrayofstring) { System.out.println ("Hello, world!" );
What's the use of getting this?
Now we have to modify the source code, the modified code is as follows.
Public class Hello { publicstaticvoid main (string[] args) { if( false ) { System.out.println ("Hello, world!" ); }
To compile, then we look at its size, only 255 bytes. How? Do you have any idea? Yes, the compiler will optimize the code, and the Java compiler will not generate bytecode for statements whose conditions are always false. Here we re-compile the class file, and the code is as follows:
Public class Hello { publicstaticvoid main (string[] paramarrayofstring) {
Using this optimization mechanism compiled by Java, we can implement the conditional compilation of Java.
Public class Hello { publicstaticvoid main (string[] args) { if (false) { System.out.println ("Hello, world!" ); }
Define a final variable and then use it in the IF statement. The code is as follows:
Public class Hello { publicstaticvoid main (string[] args) { final Boolean true ; if (DEBUG) { System.out.println ("Hello, world!" ); }
When conditional compilation is used for a long time, the above will be very detrimental to code modification and maintenance, then you can use a more flexible method. Defines a static class that specifically defines the variables used to control conditional compilation. The class is then imported into the specific code, using these final variables. The code is as follows:
Public class Debugconfig { publicstaticfinalbooleanfalse; Public Static Final Boolean false
if (debugconfig.bluetooth_debug) { //
[Java Basics] How Java implements conditional compilation