Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8: Pass object's method & its arguments as parameter

I have two classes A & B , like this:

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

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

Now I need to provide retry mechanism for both methods fetchMax() & fetchPercentile(Integer). I want to provide this behaviour using a helper class, where the retry method which can take instance of (A or B), method-name and method-arguments. The retry would basically do reattempts on the provided method of the object.

Something like this:

class Retry {
     public static R retry(T obj, Function<T, R> method,  Object... arguments) {
           // Retry logic
           while(/* retry condition */)
           {
                obj.method(arguments);
           }
     }
}
like image 831
Mohitt Avatar asked Apr 30 '26 11:04

Mohitt


1 Answers

Just take a Callable as argument:

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

And call it this way:

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

You might want to use, or get inspiration from guava-retrying, a small extension to Google's Guava library to allow for the creation of configurable retrying strategies (disclaimer: I'm the original author).

like image 115
JB Nizet Avatar answered May 03 '26 01:05

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!