Students who have studied C or C + + know that they support conditional compilation, so today we will learn how to implement conditional compilation in the Java language. The Java language itself does not provide conditional compilation, but the Java compiler has optimized the. java file for. class files, which is explained in detail by an example below.
The Helloworld.java file is given below:
1 Packagecom.test;2 3 /**4 * Test Demo5 */6 Public classHelloWorld {7 8 Public Static voidMain (string[] args) {9 if(buildconfig.flag) {TenSystem.out.println ("Hello World"); One}Else { ASYSTEM.OUT.PRINTLN ("Java conditional compilation test"); - } - } the -}
Look again at the Buildconfig.java file:
Package com.test; /** */publicfinalclass buildconfig {public Static Final Boolean false ;}
Take a look at the contents of the. java file that was converted to a. class file:
// // // (powered by Fernflower Decompiler) // Package Com.test; public class HelloWorld { HelloWorld () {} public static void main (string[] args) {System.out.println ( "Java conditional compilation test" ); }}
What is known is that Buildconfig.flag will never be executed in the FALSE,IF block code, and this part of the code will not be compiled into the. class file.
What happens if flag is a string? If comparisons are made between strings using equals, they will not be optimized when converted to a. class file.
Helloworld.java file:
package Com.test; /** * Test Demo */ public class HelloWorld { static void main (string[] args) {if (BuildConfig.FLAG.equals ("false" "Hello World" ); else {System.out.println ( "J Ava conditional Compilation test "); } }}
Helloworld.class file:
////Source code recreated from a. class file by IntelliJ idea//(Powered by Fernflower Decompiler)// Packagecom.test; Public classHelloWorld { PublicHelloWorld () {} Public Static voidMain (string[] args) {if("false". Equals ("false") {System.out.println ("Hello World"); } Else{System.out.println ("Java conditional compilation test"); } }}
If you really need a string comparison, you can use "= =" to implement conditional compilation.
Helloworld.java file:
package Com.test; /** * Test Demo */ public class HelloWorld { static void main (string[] args) {if (Buildconfig.flag = = "false" "Hello World" ); else {System.out.println ( "J Ava conditional Compilation test "); } }}
helloworld.class files:
// // Source code recreated from a. class file by IntelliJ idea // (Powered by Fernflower Decompiler) // Package com.test; Public class HelloWorld { public HelloWorld () { } publicstatic void main (string[] args) { System.out.println ("Hello World");} }
Java conditional compilation