ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java – 为什么Eclipse会抱怨死代码?

2019-05-20 15:48:17  阅读:255  来源: 互联网

标签: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;
}

我的理由是这样的:

>如果bote img0和img1不为null,则if计算为true
>如果它评估为假则

> img0为空OR
> img1为空OR
> img0和img1都为空.

>如果img0不为null,则第一个elseif求值为true,如果求值为false,则img1可能不为null或者img0和img1都为null

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

提前致谢.

解决方法:

在以下两种方式中查看代码的使用: –

方式1: –

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;
    }
}

在这种情况下,您肯定会在一个块或另一个块上获得死代码警告,因为您正在设置块之前的值,并且编译器确保这些值在初始化和执行这些块之间不会发生变化.

方式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;
    }
}

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

>如果它们都为null,则执行最后一个else.
>如果其中一个为null,则将执行其中一个else.
>并且,如果它们都不为null,则将执行if.

注意 : –

如果需要,可以将Eclipse配置为不显示某些情况的警告,例如:Unoccessary else,Unused Imports等.

Go to Windows -> Preferences -> Java (on Left Panel) -> Compiler ->
Errors/ Warnings

标签:java,eclipse,dead-code
来源: https://codeday.me/bug/20190520/1144084.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有