Java 代码分析失败:死存储到局部变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20488777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 02:16:54  来源:igfitidea点击:

Code Analysis Failure: Dead store to local variable

java

提问by c12

I have a code analysis tool that is flagging the LinkedHashSet<String> widgetsToCreate = new LinkedHashSet<String>();line in the below method, any ideas on a way to fix the logic that would satisfy the analysis tool?

我有一个代码分析工具LinkedHashSet<String> widgetsToCreate = new LinkedHashSet<String>();在下面的方法中标记该行,有什么想法可以修复满足分析工具的逻辑吗?

Dead store to local variable:

死存储到局部变量:

This instruction assigns a value to a local variable, but the value is not read or used in any subsequent instruction. Often, this indicates an error, because the value computed is never used. Note that Sun's javac compiler often generates dead stores for final local variables. Because FindBugs is a bytecode-based tool, there is no easy way to eliminate these false positives.

该指令为局部变量赋值,但该值不会在任何后续指令中读取或使用。通常,这表示有错误,因为从未使用过计算值。请注意,Sun 的 javac 编译器通常会为最终局部变量生成死存储。由于 FindBugs 是一种基于字节码的工具,因此没有简单的方法可以消除这些误报。

public void add(Map<String, String> input) {    
    TreeSet<String> widgetsToAdd = new TreeSet<String>();
    TreeSet<String> widgetsToUpdate = new TreeSet<String>();
    LinkedHashSet<String> widgetsToCreate = new LinkedHashSet<String>();

    for (Map.Entry<String, String> entry : input.entrySet()) {
      //logic to add to widgetsToAdd based on content of the input Map
    }

     widgetsToCreate = processInput(widgetsToAdd);
     for (Iterator<String> wIterator = widgetsToCreate.iterator(); wIterator.hasNext();) {
         //process each widgetsToCreate  
     }
}

采纳答案by micha

Iam not sure but I think you get the error message because you never use the assigned new LinkedHashSet<String>();

我不确定,但我认为您收到错误消息是因为您从未使用分配的 new LinkedHashSet<String>();

// LinkedHashSet assigned to widgetsToCreate 
LinkedHashSet<String> widgetsToCreate = new LinkedHashSet<String>();

// widgetsToCreate is not used
for (Map.Entry<String, String> entry : input.entrySet()) {
  //logic to add to widgetsToAdd based on content of the input Map
}

// new value assigned to widgetsToCreate, the LinkedHashSet assigned before wasn't used
widgetsToCreate = processInput(widgetsToAdd);

So you could write:

所以你可以写:

...
for (Map.Entry<String, String> entry : input.entrySet()) {
  //logic to add to widgetsToAdd based on content of the input Map
}
LinkedHashSet<String> widgetsToCreate = processInput(widgetsToAdd);

回答by MAYCON FLAUSINO

You get the error message because you never use the assigned widgetsToUpdate.

您收到错误消息是因为您从未使用分配的 widgetsToUpdate。