我怎樣才能將Java中的兩個方法doRetry變成一個通用方法doRetryA和doRetryB,這兩個方法執行類似的代碼,但不同的是 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。
}
uj5u.com熱心網友回復:
像這樣定義一個介面:
interface ThrowingBiFunction<A, B, C> {
C apply(A a, B b) throws IOException, InterruptedException;
}
然后在你的方法中接受一個這樣的實體:
private FooType doRetry(ThrowingBiFunction<AType, BType, FooType> func) {
for(int attempt=0; attempt<retries; attempt ) {
foo = func.apply(a, b);
return foo;
}
我不知道a、b或foo的型別。也許它們在兩種情況下是一樣的,也許不一樣。如果它們不一樣,就添加一些型別引數,例如:
private <AType, BType, FooType> FooType doRetry(ThrowingBiFunction<AType, BType, FooType> func) {
然后呼叫:
doRetry((a, b) -> func1(a, b)); // Or doRetry(this::func1) or similar.
doRetry((a, b) -> func2(a, b))。
uj5u.com熱心網友回復:
你可以使用字串變數傳遞你想要的函式型別,就像這樣......
SomeType foo = someEnum.enumValue;
private SomeType def doRetry(String funcType) {
for (int attempt=0; attempt< retries; attempt ) {
if (funcType.eals("ONE")) {
foo = func1(a, b);
} else if (funcType.eals("TWO"/span>)) {
foo = func2(a, b);
}
}
return foo;
}
//函式呼叫。
doRetry("ONE")。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/330165.html
標籤:
