【发布时间】:2021-11-14 21:37:18
【问题描述】:
如何在 Java 中从 doRetryA 和 doRetryB 这两个方法中创建一个方法泛型方法 doRetry,其中 moth 都执行相似的代码,但在 func1 和 func2 调用中不同,其中 func1 和 func2 采用相同数量的参数并且这些参数是相同的类型,但是 func1 和 func2 在功能上不同但返回相同的类型?
SomeType foo = someEnum.enumValue;
private SomeType def doRetryA() {
for(int attempt=0; attempt<retries; attempt++) {
foo = func1(a, b);
return foo;
}
private SomeType def doRetryB() {
for(int attempt=0; attempt<retries; attempt++) {
foo = func2(a, b);
return foo;
}
【问题讨论】:
-
只要把函数作为参数,双函数就可以了。
-
doRetry(BiFunction<TypeOfA, TypeOfB, SomeType> func) { ... foo = func.apply(a, b); ... }。然后您可以将其称为doRetry(this::func1);或doRetry(this::func2); -
func1 和 func2 都抛出 IOException、InterruptedException 和现在 doRetry 抱怨未处理的异常。
-
@darkman define
interface ThrowingBiFunction,它有一个声明为抛出检查异常的方法。 -
您没有指定,所以我们无法知道。这就是为什么在您的问题中包含所有重要信息很重要