包装具有通用功能的代码,同时传递参数

问题描述 投票:0回答:1

我有以下代码:

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块,并将它们放入包装器中,因为它们总是相同的。我考虑过使用功能接口,并且几乎可以正常工作,除了我必须将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);
    });

所以,正如我在评论中所写,有没有一种方法可以使用功能接口并从封闭方法中访问变量?

java wrapper functional-interface
1个回答
1
投票

当然,几分钟后我想出了答案。我只需要将Connection参数添加到接口:

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);
});
© www.soinside.com 2019 - 2024. All rights reserved.