获取以下 Java 代码片段:
....
else if (true){ //hard-coded as true
///launch methodA
}
else {
///launch methodA (same code as in the ` else if ` statement)
}
....
我想知道的是编译器如何处理这个问题。编译器完全删除 else if(true)
语句以便不必执行检查是否合乎逻辑,即使它被硬编码为真。特别是在 Eclipse 中,上面的代码是如何解释的?
或者在下面的场景中呢:
....
else if (true){ //hard-coded as true
///launch methodA
}
else {
///launch methodBB
}
....
在这种情况下编译器删除 else
语句不是合乎逻辑吗?因为在运行时,else
语句是无法访问的。
最佳答案
无法访问的语句在 Java 中是被禁止的,并且必须触发编译错误。 JLS 定义了什么是不可访问的语句: https://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.21
这里引用太长了,但这里是摘录(强调我的):
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.
所以答案将取决于您使用的编译器及其优化选项。
关于java - (编译器) else if(true) vs else 场景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32503355/