java – 用于关闭JDBC对象的通用助手
发布时间:2020-12-14 05:38:56 所属栏目:Java 来源:网络整理
导读:强烈建议在使用它们时关闭JDBC对象(连接,语句,结果集).但是,这会产生大量代码: Connection conn = null;Statement stm = null;ResultSet res = null;try { // Obtain connection / statement,get results,whatever...} catch (SQLException e) { // ...} fi
强烈建议在使用它们时关闭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) {}} } 现在我想通过实现一个辅助函数减少关闭对象的(重复)代码量.它将对象作为参数,并尝试使用反射调用每个对象的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 } } } } finally块可以简化为: } finally { close(res,stm,conn); } 这是一件好事吗?如果不是,原因是什么?有没有更好的办法? 解决方法
就个人而言,我不会在这种情况下使用反射,当有很多好的方法可以做到这一点而不需要它.以下是您可以做的几件事.
>使用Spring.Spring有一个 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! :) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |