在工程编译时,编译器发现部分代码是无用代码,则会提示:某一行代码是DeadCode。今天compile工程的时候发现某一个循环出现这个问题,如下:
public void mouseOver(final String[] xpathArray) { final int browserType = GlobalSettings.browserCoreType; // Selenium doesn‘t support the Safari browser if (browserType == 4) { Assert.fail("Mouseover is not supported for Safari now"); Assert.fail("Incorrect browser type"); } pause(pause); Robot rb = null; try { rb = new Robot(); } catch (AWTException e) { e.printStackTrace(); } rb.mouseMove(0, 0); try { webDriverWait.until(new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver driver) { Boolean flag = false; for (String xpath : xpathArray) { WebElement we = findElement(xpath); if (browserType == 2 || browserType == 5 || browserType == 6) { try { Actions builder = new Actions(browserCore); builder.moveToElement(we).build().perform(); flag = true; break; } catch (Exception e) { logger.error("Failed to mouseover " + xpath, e); flag = false; handleFailure(e.getMessage()); } logger.info("Mouseover " + xpath); } else if (browserType == 1 || browserType == 3) { try { for (int i = 0; i < 5; i++) {//DeadCode Actions builder = new Actions(browserCore); builder.moveToElement(we).build().perform(); logger.info("Mouseover " + xpath); flag = true; break; } }catch (Exception e) { logger.error("Failed to mouseover " + xpath, e); flag = false; handleFailure(e.getMessage()); } } } return flag; } }); }catch (Exception e){ handleFailure(e.getMessage()); }
分析了下,其实循环部分的第二次就不会再执行了,因编译器已经检查到执行后的flag的状态为true,所以给出了DeadCode的警告。而代码实际运行过程中也确实不会执行第二次。
举个例子:
if(true && true){ System.out.println("这里会一直被执行"); }else{ System.out.println("这里一直不会被执行"); }
上例中,因compiler 已经判定if的结果只会为true,所以else中的语句永远不会被执行,因此else中为DeadCode。
无法预判的语句
Boolean a = true; Boolean b = true; if(a && b){ System.out.println("这里会一直被执行"); }else{ System.out.println("这里一直不会被执行"); }
上例中,由于a 和 b是2个变量,编译器编译时,无法预判if的结果是true,因此不会警告else的内容为DeadCode。
时间: 2024-10-07 20:21:27