【问题标题】:Is SpotBugs reporting a false positive on not closing a resource here?SpotBugs 是否报告未在此处关闭资源的误报?
【发布时间】:2017-12-12 16:02:23
【问题描述】:

我有这样的代码:

public static MyObject forId(long myObjectId, Connection cxn) throws SQLException {
    try (PreparedStatement stmt = cxn.prepareStatement(selectMyObjectById))) {
        stmt.setLong(1, myObjectId);
        try (ResultSet res = stmt.executeQuery()) {
            res.next();
            return MyObject.fromResultSet(res);
        }
    }
}

对于 JDBC Statement 对象,SpotBugs 将其标识为 OBL_UNSATISFIED_OBLIGATION。这是误报吗?我的印象是 try-with-resources 将确保这些资源在所有情况下都能正确关闭。

【问题讨论】:

    标签: java try-with-resources spotbugs


    【解决方案1】:

    您的 ResultSet 和 PreparedStatement 受到您正确声明的保护。

    如果您的连接也在相关范围内得到适当处理,那么是的,这是误报。

    【讨论】:

    • 以同样的方式处理。谢谢。
    【解决方案2】:

    有问题的场景绝对是误报。

    Spotbugs 存在多个问题(截至 3.1.5):

    1. 在 try-with-resources 中使用的AutoCloseable 对象被 SpotBugs 报告(误报):

    2. 还有一个专门与ResultSetStatement 相关的问题(“关闭语句隐式关闭从它获得的结果集”):

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-18
      • 1970-01-01
      • 2020-07-05
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      相关资源
      最近更新 更多