我有以下代码:
public void createProject() throws ServiceException {
Project project = new ProjectMapper().map(pipeline);
// repeating code
Connection conn;
try {
conn = JDBCConnectionManager.getConnection(POOL_NAME, DB_CONNECTION_TIMEOUT);
} catch (SQLException e1) {
e1.printStackTrace();
throw new ServiceException(e1);
}
try {
// end repeating code
ProjectAccess.writeProject(conn, project);
// repeating code
} catch (SQLException | JsonProcessingException e) {
e.printStackTrace();
throw new ServiceException(e);
} finally {
try {
releaseConnection(conn);
} catch (Exception e) {
e.printStackTrace();
throw new ServiceException(e);
}
}
// end repeating code
}
基本上我想摆脱两个 try/catch block 并将它们放入包装器中,因为它们始终相同。
我考虑过使用函数式接口(interface),它几乎可以工作,只是我必须将 conn
变量传递到我的代码中,这不适用于我的解决方案:
@FunctionalInterface
interface DatabaseLogic {
public void execute() throws SQLException, JsonProcessingException;
}
public void executeSql(DatabaseLogic dl) throws ServiceException {
Connection conn;
try {
conn = JDBCConnectionManager.getConnection(POOL_NAME, DB_CONNECTION_TIMEOUT);
} catch (SQLException e1) {
e1.printStackTrace();
throw new ServiceException(e1);
}
try {
dl.execute(conn);
} catch (SQLException | JsonProcessingException e) {
e.printStackTrace();
throw new ServiceException(e);
} finally {
try {
releaseConnection(conn);
} catch (Exception e) {
e.printStackTrace();
throw new ServiceException(e);
}
}
}
new DatabaseRunner().executeSql(() -> {
IDataCursor pipelineCursor = pipeline.getCursor();
String projectName = IDataUtil.getString(pipelineCursor, "projectName");
// how can I access the conn object here?
ProjectAccess.deleteProject(conn, projectName);
});
那么,正如我在评论中所写,有没有办法使用函数式接口(interface)并从封闭方法访问变量?
最佳答案
哼,当然几分钟后我就明白了。我只需要将 Connection 参数添加到接口(interface)即可:
public void execute(Connection conn) throws SQLException, JsonProcessingException;
new DatabaseRunner().executeSql((conn) -> {
IDataCursor pipelineCursor = pipeline.getCursor();
String projectName = IDataUtil.getString(pipelineCursor, "projectName");
ProjectAccess.deleteProject(conn, projectName);
});
关于java - 用通用功能包装代码,同时传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60305531/