gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 20:03:52 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com