【问题标题】:how to convert two similar methods in one?如何将两种相似的方法合二为一?
【发布时间】: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&lt;TypeOfA, TypeOfB, SomeType&gt; func) { ... foo = func.apply(a, b); ... }。然后您可以将其称为doRetry(this::func1); 或doRetry(this::func2);
  • func1 和 func2 都抛出 IOException、InterruptedException 和现在 doRetry 抱怨未处理的异常。
  • @darkman define interface ThrowingBiFunction,它有一个声明为抛出检查异常的方法。
  • 您没有指定,所以我们无法知道。这就是为什么在您的问题中包含所有重要信息很重要

标签: java generics types


【解决方案1】:

你可以像这样使用字符串变量传递你想要的函数类型......

SomeType foo = someEnum.enumValue;

private SomeType def doRetry(String funcType) {
    for (int attempt=0; attempt<retries; attempt++) {
        if (funcType.equals("ONE")) {
            foo = func1(a, b);
        } else if (funcType.equals("TWO")) {
            foo = func2(a, b);
        }
    }
    return foo;
}

//function call
doRetry("ONE");

【讨论】:

    【解决方案2】:

    像这样定义一个接口:

    interface ThrowingBiFunction<A, B, C> {
      C apply(A a, B b) throws IOException, InterruptedException;
    }
    

    然后在你的方法中接受 this 的一个实例:

    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));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-04
      相关资源
      最近更新 更多