使用 Checkstyle 防止预准备语句泄漏
假设我有以下代码:
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.createStatement(myQueryString);
rs = ps.executeQuery();
// process the results...
} catch (java.sql.SQLException e) {
log.error("an error!", e);
throw new Exception("I'm sorry. Your query did not work.");
} finally {
ps.close(); // if we forgot to do this we leak
rs.close(); // if we forgot to do this we leak
}
并且我希望捕获忘记使用 Checkstyles 关闭 PreparedStatement
或 ResultSet
的场景。这可能吗?如果可以,我该怎么做?
Lets say I have the following code :
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.createStatement(myQueryString);
rs = ps.executeQuery();
// process the results...
} catch (java.sql.SQLException e) {
log.error("an error!", e);
throw new Exception("I'm sorry. Your query did not work.");
} finally {
ps.close(); // if we forgot to do this we leak
rs.close(); // if we forgot to do this we leak
}
and I wished to catch the scenario where I forget to close the PreparedStatement
or the ResultSet
using Checkstyles. Is this possible, and if so, how would I go about it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
PMD 和 Findbugs 都有针对PreparedStatements(以及ResultSets 和Connections)的警告。我建议将它们用于此类警告,因为 CheckStyle 更多地与代码样式有关,而不是查找此类数据流错误。
PMD and Findbugs both have warnings for PreparedStatements (and ResultSets and Connections). I'd suggest using them for this type of warning, since CheckStyle has more to do with code style than finding data-flow bugs such as this.
我们创建了一个自定义的 Checkstyle 检查来防止这些语句泄漏。代码在下面。
checkstyle 的优点在于,您可以使用 API 公开 Java AST。
我们已经创建了数十个自定义检查。一旦掌握了要点,创建新的检查就很容易了。
我们还创建了一个 Subversion 预提交挂钩,用于运行检查并防止违规代码进入存储库。开发人员会收到一条明确的消息(请参阅下面的“日志”调用),指示问题和线路。
此自定义检查扩展了一个抽象类,其中包含两个实用程序方法,如下所示。
We created a custom Checkstyle Check that prevents these Statement leaks. The code is down below.
The beauty of checkstyle is that you can customize your checks using an API that exposes the Java AST.
We have created tens of custom checks. Once you get the gist of it, creating new checks is easy.
We have also created a Subversion pre-commit hook that runs the check and prevents code with violations to get into the repository. The developer gets a clear message (see 'log' call below) indicating the problem and the line.
This custom check extends an abstract class that contains two utility methods shown below.