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)
这是一件好事吗?如果不是,原因是什么?有没有更好的办法?
就个人而言,我不会在这种情况下使用反射,当有很多好的方法可以做到这一点而不需要它.以下是您可以做的几件事.
JdbcTemplate对象有助于减轻Jdbc编码的冗余.样板代码隐藏在实现中JdbcTemplate,因此您可以自由地对您的应用程序执行重要操作.AutoClosable接口的对象. 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)