java - Java 对带有 final 变量的 if 语句有多聪明

标签 java debugging if-statement final

我想写一些故障排除代码,我可以很容易地从我的程序的以后的非调试版本中删除这些代码。我想到了:

final static boolean debug_on=true;
...
if (debug_on) { system.out.println() or logger.log(...) }

如果 debug==false,Java 是否足够聪明,可以从最终字节码中删除 if 语句?

是否有更好的做法来实现将调试代码排除在程序的最终版本之外的目标?

最佳答案

请参阅 Java language specification chapter 14.21. Unreachable Statements 的末尾if(false) 的描述:

if (false) { x=3; }

does not result in a compile-time error. An optimizing compiler may realize that the statement x=3; will never be executed and may choose to omit the code for that statement from the generated class file, but the statement x=3; is not regarded as "unreachable" in the technical sense specified here.

The rationale for this differing treatment is to allow programmers to define "flag variables" such as:

static final boolean DEBUG = false;

and then write code such as:

if (DEBUG) { x=3; }

The idea is that it should be possible to change the value of DEBUG from false to true or from true to false and then compile the code correctly with no other changes to the program text.

tl;dr; 字节码中是否省略了 if 中的语句取决于编译器。

关于java - Java 对带有 final 变量的 if 语句有多聪明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15906596/

相关文章:

java - Hibernate 合并父级并更新惰性子级集合列表

java - 连接到多个集群spring kafka

java - BufferedWriter 未写入文件

c - 在调试器下运行 perl 程序,直到满足某些条件

java - if-else 替代方案

java - 在给定基本 URL 和带有参数的 Map<String,String> 的情况下对 URL 进行编码的标准方法

PHP 错误日志和换行符

java - 如何处理java中的bug "dead store to local variable"?

java - 从条件树中排除分支,删除未使用的代码

php - 数组声明中的 if 语句...这可能吗?