"finally" 子句中 "Use try-with-resources or close this "ResultSet" 的 Sonarqube 误报"

Sonarqube false positive for "Use try-with-resources or close this "ResultSet" in a "finally" clause"

Sonarqube 一直用这个问题标记代码,在我看来,这是一个误报。 代码如下所示:

try(PreparedStatement st=con.prepareStatement(myQuery)){
    st.setInt(1, myValue);
    ...
    ResultSet rs = st.executeQuery();
    ...
}

如果我没记错的话,PreparedStatement 实现了 Closeable,并且在关闭自身时,它也会关闭底层的 ResultSet。

此行为会阻止 ResultSet 保持打开状态,但 Sonarqube 分析将其标记为严重错误。

我错了吗? 在这种情况下?

在 Sonarqube 6.7.3 和 JDK 8 下测试。

来自 ResultSet javadoc:

A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results.

There's no properties file or any configuration in the pom.xml file

请看这个documentation, you can create sonar-project.properties file in your root project directory set a lot of diffrent properties which have impact on your analysis. One of them is sonar.java.source which allow you specific concreate java version. (details)

Any way of making Sonarqube ignore this rule under this circumstances?

我遇到过 sonarqube 引擎将代码块标记为问题的情况,但从开发人员的角度来看并非如此,因此在这种情况下,可以将其标记为误报。要设置 allow/disallow 标记特定文件问题的规则,请参考此 sonarqube documentation

期望代码分析器知道这些事情可能是不合理的。一个工具能否知道随时随地编写的所有库中所有 Closeable 的所有 - 附加 - 语义?

doco 确实提到 "the current ResultSet, if any, is also closed"。

备注"the current"。如果您碰巧有两个不同的 executeQuery() 调用会怎样?它会因状态不佳或类似原因而失败吗?是否会有两个不同的 ResultSet 对象,两者都未关闭,其中一个现在未被引用?

(注意:两个不同的 executeQuery() 调用听起来可能完全疯了,但请记住 "coders can do anything" 这甚至是 原因为什么先写SonarQube等工具。)

我并不是说这完全没有争议,但对我来说,如果分析工具只是看到您获得了一个 Closeable 而没有关闭它并且只是简单地抱怨它,这似乎并不奇怪。

确实这是误报。它已经被报告并且有公开的票来修复它 https://jira.sonarsource.com/browse/SONARJAVA-2060

您可以在 SonarQube UI 中将问题标记为误报,或者在提出问题的行中添加 // NOSONAR 评论以忽略它。

6.7 版本开始,Sonarqube 团队最终解决了这个问题。