【发布时间】:2017-07-07 16:54:45
【问题描述】:
这是一个问题,不是问题。
我有一个名为 DSConnectionUtilExternal 的类,它有一个检索数据库连接的方法和一个关闭它的方法。这个类在一个 jar 文件中。
另一方面,我有一个项目,其中包含 jar 文件作为依赖项。 在这个项目中我有这个代码
Connection con = null;
ResultSet rsGet = null;
PreparedStatement psGet = null;
try {
con = DSConnectionUtilExternal.openConnection();
psGet = con.prepareStatement("SELECT * FROM TEST");
rsGet = psGet.executeQuery();
int counter = 0;
while (rsGet.next()) {
counter++;
System.err.println(counter);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rsGet != null) {
rsGet.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
rsGet = null;
try {
if (psGet != null) {
psGet.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
psGet = null;
DSConnectionUtilExternal.closeConnection(con);
}
如果我在 jar 文件中删除方法 closeConnection 的内容,声纳不会检测到连接没有关闭。我觉得很正常,sonar没有反编译jar文件来访问jar文件代码。
所以问题是? “资源应该关闭”规则在finally子句中判断连接是否关闭的标准是什么?
谢谢
【问题讨论】:
-
你有充分的理由不使用 try-with-resources 吗?
-
使用的标准是引用类型是否实现 (Auto)Closeable 接口:您要么必须显式地
close()它,要么使用 try-with-resources。 -
如果您愿意对您的问题进行拼写检查,那么您被认真对待的可能性就会大得多。