我有一些函数在 catch
block 中执行相同类型的操作。
private void fun1(int a){
try{
// do api calls
}catch(Exception e){
refreshToken();
fun1(a);
}
}
private int fun2(int a, String b){
try{
// do api calls
}catch(Exception e){
refreshToken();
fun2(a,b);
}
}
private void fun3(String a, long b, char c){
try{
// do api calls
}catch(Exception e){
refreshToken();
fun3(a,b,c);
}
}
这里,当应用程序 token 过期时,我需要调用一个函数来获取新 token ,并且需要调用父函数。
在catch block 中,代码是重复的。所以我想在一个函数中执行这些操作。为此,我需要传递函数和参数。可以用 Java 实现吗?
最佳答案
如果您更频繁地需要此类功能,您可能需要为此构建自己的支持实用程序(然后您也可以根据需要进行改进),例如:
public class Retry {
public static <T> T endlessTryCall(Callable<T> callable, Consumer<Exception> exceptionHandler) {
for(;;) try {
return callable.call();
} catch (Exception e) {
exceptionHandler.accept(e);
}
}
public static void endlessTryRun(Runnable runnable, Consumer<Exception> exceptionHandler) {
for(;;) try {
runnable.run();
return;
} catch (Exception e) {
exceptionHandler.accept(e);
}
}
}
您的函数可能如下所示:
private void fun1(int a){
Retry.endlessTryRun(() -> {
// the API calls
}, e -> refreshToken());
}
private int fun2(int a, String b){
return Retry.endlessTryCall(() -> {
// the API calls
return ...;
}, e -> refreshToken());
}
private void fun3(String a, long b, char c){
Retry.endlessTryRun(() -> {
// the API calls
}, e -> refreshToken());
}
其他改进可能是使用诸如 tryCall(numberOfTrials, ...)
之类的函数或其他按照您需要的方式处理异常的函数。演示后者:
private void fun1(int a){
refreshTokenOnException(() -> {
// the API calls
});
}
private int fun2(int a, String b){
return refreshTokenOnException(() -> {
// the API calls
return ...;
});
}
private void fun3(String a, long b, char c){
refreshTokenOnException(() -> {
// the API calls
});
}
private <T> T refreshTokenOnException(Callable<T> callable) {
return Retry.endlessTryCall(callable, e -> refreshToken());
}
private void refreshTokenOnException(Runnable runnable) {
Retry.endlessTryRun(runnable, e -> refreshToken());
}
拥有这样一个实用程序的好处可能值得怀疑。我认为关于所做的事情有点详细。但话又说回来,人们必须为它找到合适的名称......所以......这一如既往地取决于。
关于java - 将函数和参数传递给另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56272297/