本文共 1245 字,大约阅读时间需要 4 分钟。
(1)如果if的条件是false,则在编译时忽略这个if语句。
(2)忽略未使用的变量。
下面举一个例子来证明上面的观点。
- public class ConditionalCompilation01
- {
- public static void main(String[] args) {
- final boolean flag = false;
- int a = 1;
- if(flag)
- {
- System.out.println("hello");
- }
- }
- }
生成class文件后,用jad反编译后结果如下:
- public class ConditionalCompilation01
- {
-
- public ConditionalCompilation01()
- {
- }
-
- public static void main(String args[])
- {
- }
- }
其中 a 是未使用的变量,而因为flag是final的,且为false,因此编译器也将其忽略。
条件编译应用
场景:实现一个区分DEBUG和RELEASE模式的程序。
通常为了让Java条件编译更加方便,我们创建一个类:CompilationConfig。
- class CompilationConfig
- {
- static final boolean DEBUG_MODE = true;
- static final boolean RELEASE_MODE = false;
- }
从上面可以看出,这个类有如下特点:
- 全部都是static final boolean常量。
- 如果是debug模式,则DEBUG_MODE=true;
- 如果是release模式,则RELEASE_MODE=true;
- public class ConditionalCompilation02
- {
- public static void main(String[] args) {
- if(CompilationConfig.DEBUG_MODE)
- {
- System.out.println("[DEBUG MODE]You can print sth");
- }
- else
- {
- System.out.println("[RELEASE MODE]You can print sth");
- }
- }
- }
如果DEBUG_MODE=true,则class文件编译后,用jad反编译为如下代码:
- import java.io.PrintStream;
-
- public class ConditionalCompilation02
- {
-
- public ConditionalCompilation02()
- {
- }
-
- public static void main(String args[])
- {
- boolean flag = true;
- System.out.println("[DEBUG MODE]You can print sth");
- }
from:
转载地址:http://qtwrf.baihongyu.com/