Java 8:传递对象的方法&它的参数作为参数

时间:2017-11-01 15:39:18

标签: java design-patterns lambda java-8

我有两个课程A& B,就像这样:

class A {
    public Integer fetchMax() {
       // Make a network call & return result
    } 
}

class B {
    public Double fetchPercentile(Integer input) {
        // Make a network call & return result
    } 
}

现在我需要为两种方法retry&提供fetchMax()机制。 fetchPercentile(Integer)。我想使用helper类来提供此行为,其中retry方法可以使用instance(A或B),method-namemethod-arguments。重试基本上会对提供的对象方法进行重新尝试。

这样的事情:

class Retry {
     public static R retry(T obj, Function<T, R> method,  Object... arguments) {
           // Retry logic
           while(/* retry condition */)
           {
                obj.method(arguments);
           }
     }
}

1 个答案:

答案 0 :(得分:8)

只需要Callable作为参数:

public static <R> R retry(Callable<R> action) {
    // Retry logic
    while(/* retry condition */) {
        action.call();
    }
}

并以这种方式称呼它:

Retry.retry(() -> a.fetchMax());
Retry.retry(() -> b.fetchPercentile(200));

您可能希望使用guava-retrying作为Google Guava library的一个小扩展程序来获取灵感,以便创建可配置的重试策略(免责声明:I&#39; m原作者)。

相关问题