为什么Eclipse会抱怨死代码?

eva*_*ing 5 java eclipse dead-code

Eclipse继续说明最后的elseif和else是死代码,但我不明白.

if (img0 != null && img1 != null) {
    code;

} else if (img0 != null) {
    code;
} else if (img1 != null) {
    code;
} else {
    code;
}
Run Code Online (Sandbox Code Playgroud)

我的理由是这样的:

  1. 如果bote img0和img1不为null,则if计算为true
  2. 如果它评估为假则
    • img0为空OR
    • img1为空OR
    • img0和img1都是null.
  3. 如果img0不为null,则第一个elseif求值为true,如果求值为false,则img1可能不为null或者img0和img1都为null

我错过了什么,"死亡"在哪里?

提前致谢.

Roh*_*ain 4

通过这两种方式查看您的代码的使用情况:-

方式一:-

public static void main(String[] args)
{
    String img0 = null;
    String img1 = "Asdf";

    /** Currently there is no code here, that can modify the value of 
        `img0` and `img1` and Compiler is sure about that. 
    **/

    /** So, it's sure that the below conditions will always execute in a
        certain execution order. And hence it will show `Dead Code` warning in 
        either of the blocks depending upon the values.
    **/

    if (img0 != null && img1 != null) {
       // code;

    } else if (img0 != null) {
        //code;

    } else if (img1 != null) {
        //code;
    } else {
       // code;
    }
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您肯定会dead code在一个块或另一个块上收到警告,因为您在块之前设置值,并且编译器确保这些值在这些块的初始化和执行之间不会更改。

方式2:-

public static void main(String[] args)
{
    String img0 = null;
    String img1 = "Asdf";

    show(img0, img1);
}

public static void show(String img0, String img1) {

    /** Now here, compiler cannot decide on the execution order, 
        as `img0` and `img1` can have any values depending upon where 
        this method was called from. And hence it cannot give dead code warning.
    **/

    if (img0 != null && img1 != null) {
       // code;

    } else if (img0 != null) {
        //code;

    } else if (img1 != null) {
        //code;
    } else {
       // code;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,在这种情况下,您不会收到dead code警告,因为编译器不确定从哪里show调用该方法。img0和的值img1可以是方法内的任何值。

  • 如果两者都是,则执行null最后一个。else
  • 如果one of them is null,其中之一else if将被执行。
  • 而且,如果他们都没有null,你的意志if就会被执行。

笔记 : -

如果需要,您可以将 Eclipse 配置warnings为在某些情况下不显示,例如 - Unneccessary elseUnused Imports等。

转到 Windows -> 首选项 -> Java(在左侧面板上) -> 编译器 -> 错误/警告