博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java知识点:条件编译
阅读量:2119 次
发布时间:2019-04-30

本文共 1245 字,大约阅读时间需要 4 分钟。

(1)如果if的条件是false,则在编译时忽略这个if语句。

(2)忽略未使用的变量。

下面举一个例子来证明上面的观点。

 
  1. public class ConditionalCompilation01
  2. {
  3. public static void main(String[] args) {
  4. final boolean flag = false;
  5. int a = 1;
  6. if(flag)
  7. {
  8. System.out.println("hello");
  9. }
  10. }
  11. }

生成class文件后,用jad反编译后结果如下:

 
  1. public class ConditionalCompilation01
  2. {
  3.  
  4. public ConditionalCompilation01()
  5. {
  6. }
  7.  
  8. public static void main(String args[])
  9. {
  10. }
  11. }

其中 a 是未使用的变量,而因为flag是final的,且为false,因此编译器也将其忽略。

条件编译应用

场景:实现一个区分DEBUG和RELEASE模式的程序。

通常为了让Java条件编译更加方便,我们创建一个类:CompilationConfig。

 
  1. class CompilationConfig
  2. {
  3. static final boolean DEBUG_MODE = true;
  4. static final boolean RELEASE_MODE = false;
  5. }

从上面可以看出,这个类有如下特点:

  • 全部都是static final boolean常量。
  • 如果是debug模式,则DEBUG_MODE=true;
  • 如果是release模式,则RELEASE_MODE=true;
 
  1. public class ConditionalCompilation02
  2. {
  3. public static void main(String[] args) {
  4. if(CompilationConfig.DEBUG_MODE)
  5. {
  6. System.out.println("[DEBUG MODE]You can print sth");
  7. }
  8. else
  9. {
  10. System.out.println("[RELEASE MODE]You can print sth");
  11. }
  12. }
  13. }

如果DEBUG_MODE=true,则class文件编译后,用jad反编译为如下代码:

 
  1. import java.io.PrintStream;
  2.  
  3. public class ConditionalCompilation02
  4. {
  5.  
  6. public ConditionalCompilation02()
  7. {
  8. }
  9.  
  10. public static void main(String args[])
  11. {
  12. boolean flag = true;
  13. System.out.println("[DEBUG MODE]You can print sth");
  14. }

from:  

转载地址:http://qtwrf.baihongyu.com/

你可能感兴趣的文章
逆序对的数量(递归+归并思想)
查看>>
数的范围(二分查找上下界)
查看>>
算法导论阅读顺序
查看>>
Windows程序设计:直线绘制
查看>>
linux之CentOS下文件解压方式
查看>>
Django字段的创建并连接MYSQL
查看>>
div标签布局的使用
查看>>
HTML中表格的使用
查看>>
(模板 重要)Tarjan算法解决LCA问题(PAT 1151 LCA in a Binary Tree)
查看>>
(PAT 1154) Vertex Coloring (图的广度优先遍历)
查看>>
(PAT 1115) Counting Nodes in a BST (二叉查找树-统计指定层元素个数)
查看>>
(PAT 1143) Lowest Common Ancestor (二叉查找树的LCA)
查看>>
(PAT 1061) Dating (字符串处理)
查看>>
(PAT 1118) Birds in Forest (并查集)
查看>>
数据结构 拓扑排序
查看>>
(PAT 1040) Longest Symmetric String (DP-最长回文子串)
查看>>
(PAT 1145) Hashing - Average Search Time (哈希表冲突处理)
查看>>
(1129) Recommendation System 排序
查看>>
PAT1090 Highest Price in Supply Chain 树DFS
查看>>
(PAT 1096) Consecutive Factors (质因子分解)
查看>>