【问题标题】:Code Analysis Failure: Dead store to local variable代码分析失败:死存储到局部变量
【发布时间】:2013-12-10 07:45:47
【问题描述】:

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

死存储到局部变量:

该指令为局部变量赋值,但在任何后续指令中都不会读取或使用该值。通常,这表示错误,因为计算的值从未使用过。请注意,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  
     }
}

【问题讨论】:

    标签: java


    【解决方案1】:

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

    // 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);
    

    所以你可以写:

    ...
    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);
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 您的回答应该是评论。它绝不会回答 OP 的问题。请附上如何assignwidgetsToUpdate的代码示例,然后我们将有一个适当的、高质量的答案。
      猜你喜欢
      • 1970-01-01
      • 2014-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-24
      • 1970-01-01
      相关资源
      最近更新 更多