The SelfCleaningResultSet class is a proxy for JDBC that uses delegation to delgate to a ResultSet, but also calls close() on a Statement when the ResultSet is closed.
import java.lang.reflect.*;
import java.sql.ResultSet;
import java.sql.Statement;
public class SelfCleaningResultSet implements java.lang.reflect.InvocationHandler{
private ResultSet rs;
private Statement s;
public static ResultSet wrap(ResultSet rs, Statement s){
return (ResultSet) Proxy.newProxyInstance(
rs.getClass().getClassLoader(),
rs.getClass().getInterfaces(),
new SelfCleaningResultSet(rs,s));
}
private SelfCleaningResultSet(ResultSet rs,Statement s){
this.rs=rs;
this.s=s;
}
public Object invoke(Object proxy, Method m, Object[] args) throws
Throwable{
Object result;
try {
result = m.invoke(rs, args);
if (m.getName().equals("close"))
s.close();
} catch (InvocationTargetException e) {
throw e.getTargetException();
} catch (Exception e) {
throw new RuntimeException("unexpected invocation exception: " +
e.getMessage());
}
return result;
}
}