It is strongly suggested to close JDBC objects (connections, statements, result sets) when done using them. However, that produces loads of code like that:
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 thought about reducing the amount of (repeating) code for closing the objects by implementing a helper function. It takes the objects as arguments and tries to invoke the method close() of each object (if the object does have 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; // break on the methods, go for the next object
}
}
}
}
The finally block can be reduced to this:
} finally {
close(res, stm, conn);
}
Is that a good thing to do? If no, what are the reasons? Is there a "better" way?