如何重新组合catch最终成为java 8中的一个方法?

hen*_*ang 9 java java-8

Java 8新手,我想优化我的代码:

public Response create() {
    try{
        ...
    } catch (Exception e) {
        codeA;
    } finally {
        codeB;
    }
}

public Response update() {
    try{
        ...
    } catch (Exception e) {
        codeA;
    } finally {
        codeB;
    }
}
Run Code Online (Sandbox Code Playgroud)

我有很多方法使用相同的方法来捕获异常并最终做同样的事情,是否有可能用java 8中的方法替换下面的公共代码?这样我就可以优化使用这个通用代码的所有方法.

} catch (Exception e) {
    codeA;
} finally {
    codeB;
}
Run Code Online (Sandbox Code Playgroud)

And*_*ner 15

取决于你在做什么....你可以这样做:

private Response method(Supplier<Response> supplier) {
    try{
        return supplier.get();
    } catch (Exception e) {
        codeA;
    } finally {
        codeB;
    }
}
Run Code Online (Sandbox Code Playgroud)

并调用如下:

public Response create() { return method(() -> { ... for create }); }
public Response update() { return method(() -> { ... for update }); }
Run Code Online (Sandbox Code Playgroud)


ole*_*nik 8

你可以包装你的payload并将它放到单独的方法中.一件事; 你期望在异常捕获中返回什么?这次是null,但可能你可以提供默认值.

public static <T> T execute(Supplier<T> payload) {
    try {
        return payload.get();
    } catch(Exception e) {
        // code A
        return null;
    } finally {
        // code B
    }
}
Run Code Online (Sandbox Code Playgroud)

客户端代码可能如下所示:

public Response create() {
    return execute(() -> new CreateResponse());
}

public Response update() {
    return execute(() -> new UpdateResponse());
}
Run Code Online (Sandbox Code Playgroud)