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)
我的理由是这样的:
我错过了什么,"死亡"在哪里?
提前致谢.
通过这两种方式查看您的代码的使用情况:-
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在一个块或另一个块上收到警告,因为您在块之前设置值,并且编译器确保这些值在这些块的初始化和执行之间不会更改。
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最后一个。elseone of them is null,其中之一else if将被执行。null,你的意志if就会被执行。笔记 : -
如果需要,您可以将 Eclipse 配置warnings为在某些情况下不显示,例如 - Unneccessary else、Unused Imports等。
转到 Windows -> 首选项 -> Java(在左侧面板上) -> 编译器 -> 错误/警告