It is highly recommended that you close JDBC objects (joins, statements, result sets) when they are executed using them. However, this creates many such codes:
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) {}} }
Now I was thinking about reducing the amount of (repeating) code to close objects by implementing a helper function. It takes objects as arguments and tries to call the close() method for each object (if the object has such a method) using reflection.
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;
The finally block can be summarized as follows:
} finally { close(res, stm, conn); }
This is a good thing? If not, what are the reasons? Is there a "better" way?
source share