我有JDBC語句執行有許多方法的一些包裝類,像下面:的Java 8拉姆達風格包裝的JDBC語句的執行
public ResultSet executeQuery(String sql) {
try (Statement statement = this.connection.createStatement()) {
return statement.executeQuery(sql);
} catch (SQLException e) {
throw new RuntimeException("My custom statement execution failure", e);
}
}
public int executeUpdate(String sql) {
try (Statement statement = this.connection.createStatement()) {
return statement.executeUpdate(sql);
} catch (SQLException e) {
throw new RuntimeException("My custom statement execution failure", e);
}
}
...
所以有很多的方法,這些方法的不同僅1)返回類型和2)實際的委託方法。
我想通過可執行呼叫Ruby的拉姆達時尚,以減少樣板代碼是這樣的:
public Boolean executeQuery(String sql) {
return wrapException(s -> {s.executeQuery(sql)});
}
private <T> wrapException(Function<Statement, <T>> query)throws Exception {
try (Statement statement = this.connection.createStatement()) {
return query.apply(statement);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
兩件事情我目前無法繞到我的頭是:
- 如何保留wrappedQuery函數的通用返回類型
- s.executeQuerty(sql)仍然抱怨未處理的SQLException, 如此有效我無法將所有異常處理way
任何想法?
您忘了將'wrapException'重命名爲'wrappedQuery'嗎? – nullpointer
@nullpointer噢,謝謝,複製/粘貼問題:) –