以这两种方式查看您的代码的使用情况:-
方式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;
}
}
在这种情况下,您肯定会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;
}
}
现在,在这种情况下,您不会收到dead code
警告,因为 Compiler 不确定从何处show
调用该方法。img0
和的值img1
可以是方法内的任何值。
- 如果两者都是,则将执行
null
最后一个。else
- 万一
one of them is null
,其中之一else if
将被执行。
- 并且,如果它们都不是
null
,您if
将被执行。
笔记 : -
如果需要,您可以将 Eclipse 配置warnings
为在某些情况下不显示,例如 - Unneccessary else
、Unused Imports
等。
转到 Windows -> 首选项 -> Java(在左侧面板上)-> 编译器 -> 错误/警告