java – 为什么Eclipse会抱怨死代码?
作者:互联网
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