用于关闭JDBC对象的通用帮助器

rih*_*iha 6 java reflection jdbc

强烈建议在使用它们时关闭JDBC对象(连接,语句,结果集).但是,这会产生大量代码:

Connection conn = null;
Statement stm = null;
ResultSet res = null;
try {
  // Obtain connection / statement, get results, whatever...
} catch (SQLException e) {
  // ...
} finally {
  if (res != null) { try { res.close(); } catch (SQLException ignore) {}}
  if (stm != null) { try { stm.close(); } catch (SQLException ignore) {}}
  if (conn != null) { try { conn.close(); } catch (SQLException ignore) {}}
}
Run Code Online (Sandbox Code Playgroud)

现在我想通过实现一个辅助函数减少关闭对象的(重复)代码量.它将对象作为参数,并尝试close()使用反射来调用每个对象的方法(如果对象确实具有这样的方法).

public void close(Object... objects) {
  for (Object object : objects) {
    for (Method method : object.getClass().getMethods()) {
      if (method.getName().equals("close")) {
        try {
          method.invoke(object);
        } catch (Exception e) {
          e.printStackTrace();
        }
        break; // break on the methods, go for the next object
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

finally块可以简化为:

} finally {
  close(res, stm, conn);
}
Run Code Online (Sandbox Code Playgroud)

这是一件好事吗?如果不是,原因是什么?有没有更好的办法?

nic*_*ild 8

就个人而言,我不会在这种情况下使用反射,当有很多好的方法可以做到这一点而不需要它.以下是您可以做的几件事.

  1. 使用Spring.Spring有一个JdbcTemplate对象有助于减轻Jdbc编码的冗余.样板代码隐藏在实现中JdbcTemplate,因此您可以自由地对您的应用程序执行重要操作.
  2. 使用Java7.Java7提供了一种新的语言结构,可以更容易地关闭实现该AutoClosable接口的对象.
  3. 创建自己的库来处理样板代码.如果Spring对您的需求太重,您可以在一个基类中轻松完成所有关闭,Jdbc交互类可以从中扩展.你将不得不写一次,但它在大多数情况下都可以不在视线之内.

Java7方式看起来像这样:

try (
    Connection conn = getConnectionSomehow();
    Statement statement = getStatementFromConnSomehow(conn);
) {
    //use connection
    //use statement
} catch(SomeException ex) {
    //do something with exception
}//hey, check it out, conn and statement will be closed automatically! :)
Run Code Online (Sandbox Code Playgroud)