编程语言
首页 > 编程语言> > java – 在else中明显的错误条件,如果不给内部的死代码

java – 在else中明显的错误条件,如果不给内部的死代码

作者:互联网

通过我的一个队友写的一些旧代码,我发现这个奇怪的代码:

if (...) {
    // some code

} else if (this == null) {
    System.out.println("I expected this to be dead code!");
}

奇怪的不是它. AFAIK,这个== null条件永远不会是真的,这对编译器来说应该是显而易见的,因为它知道这个的含义和null两者.但令我惊讶的是,这并没有标记为死代码.

我在Eclipse中通过命令行尝试了这段代码.我运行以下命令来启用所有警告:

javac -Xlint:all MyClass.java

它还没有发出任何警告.

相反,如果我将else if块更改为:

else if (false) {
    System.out.println("As expected, this is dead code");
}

正如我所料,内部声明被标记为死代码.

那为什么会这样呢?这只会让我觉得可能存在一些实际上可能为空的情况.是吗?

解决方法:

JLS has a definition of unreachable code

The analysis takes into account the structure of statements. Except for the special treatment of while, do, and for statements whose condition expression has the constant value true, the values of expressions are not taken into account in the flow analysis.

所以这不被认为是“无法到达”.

另请参阅this discussion有关无法访问的代码错误和死代码警告.

标签:java,this,eclipse,if-statement,dead-code
来源: https://codeday.me/bug/20190529/1176483.html