4

Going through some old code written by one of my teammate, I found this really strange code:

if (...) {
    // some code

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

Strange isn't it. AFAIK, this == null condition can never be true, which should be obvious to the compiler, as it knows the meaning of this and null both. But to my surprise, that wasn't marked as dead code.

I tried this code both in Eclipse, and through command line. I ran the following command to enable all warning:

javac -Xlint:all MyClass.java

Still it didn't gave any warning.

On contrary, if I change the else if block to:

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

The statement inside was marked as dead code, as I expected.

So why this behaviour? This only leads me to think that there might be some condition where this can actually be null. Is it?

4

3 回答 3

6

JLS 有一个不可访问代码的定义:

该分析考虑了语句的结构。除了特殊处理while、do和条件表达式为真值的语句外,流分析中不考虑表达式的值。

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

另请参阅有关无法访问的代码错误和死代码警告的讨论。

于 2013-10-08T10:35:00.597 回答
0

编译器在检测隐式总是错误的条件方面似乎参差不齐,即使 JLS 暗示或声明它/显然是错误的,它也可能不会接受这一事实。当简单地列出一组要检查的“明显条件”时,is-null 检查并不那么简单,因此它可能被忽略了。

于 2013-10-08T10:32:35.350 回答
0

赖斯定理意味着检查 Java 表达式的计算结果是否false是不可判定的。即理论上不可能确定某些任意代码是否已死。

由于 Java 编译器无法检测到所有死代码,因此开发人员选择了一组他们可以检测到的非常具体的死代码实例。

于 2014-07-16T22:48:23.950 回答