对于java 8,我想对下面的代码进行优化:
public Response create() {
try{
...
} catch (Exception e) {
codeA;
} finally {
codeB;
}
}
public Response update() {
try{
...
} catch (Exception e) {
codeA;
} finally {
codeB;
}
}我有很多方法使用同样的方法来捕获异常,最后,是否可以用java 8中的方法替换下面的公共代码?这样我就可以优化使用这些通用代码的所有方法。
} catch (Exception e) {
codeA;
} finally {
codeB;
}发布于 2019-01-04 14:53:41
这取决于您在...中做了什么。你可以这样做:
private Response method(Supplier<Response> supplier) {
try{
return supplier.get();
} catch (Exception e) {
codeA;
} finally {
codeB;
}
}并引用如下:
public Response create() { return method(() -> { ... for create }); }
public Response update() { return method(() -> { ... for update }); }发布于 2019-01-04 14:55:55
您可以包装您的payload并将其放到单独的方法中。一件事,你期望在异常捕获时返回什么。这一次是null,但是您可能可以提供默认值。
public static <T> T execute(Supplier<T> payload) {
try {
return payload.get();
} catch(Exception e) {
// code A
return null;
} finally {
// code B
}
}客户端代码可能如下所示:
public Response create() {
return execute(() -> new CreateResponse());
}
public Response update() {
return execute(() -> new UpdateResponse());
}发布于 2019-01-04 15:09:35
这可能是一个通用的解决方案。
//here describe supplier which can throw exceptions
@FunctionalInterface
public interface ThrowingSupplier<T> {
T get() throws Exception;
}
// The wrapper
private <T> T callMethod(ThrowingSupplier<T> supplier) {
try {
return supplier.get();
} catch (Exception e) {
//code A
}finally {
// code B
}
}https://stackoverflow.com/questions/54041246
复制相似问题