使用lambda参数实现
时间: 2023-12-03 22:04:43 浏览: 22
当使用 Lambda 表达式作为参数时,您可以将 `Callable` 替换为 `Supplier`,因为它不需要传递任何参数。以下是使用 Lambda 参数的 `RetryWrapper` 实现:
```java
public class RetryWrapper {
public static <T> T retry(int maxAttempts, Supplier<T> supplier) throws Exception {
int attempt = 0;
while (true) {
try {
return supplier.get();
} catch (Exception e) {
if (++attempt >= maxAttempts) {
throw e;
}
logError(e, attempt);
}
}
}
private static void logError(Exception e, int attempt) {
// your code here to log the error with attempt number
System.out.println("Attempt " + attempt + " failed with error: " + e.getMessage());
}
}
```
调用示例:
```java
int result = RetryWrapper.retry(3, () -> {
// your code here
return someValue;
});
```
在上述示例中,我们使用 `Supplier` 作为函数参数,Lambda 表达式包含要重试的代码。如果出现异常,`RetryWrapper` 类将记录异常信息并重新尝试执行代码,最多重试 `maxAttempts` 次。