简体   繁体   English

这种方法如何引用一个有效的? 幕后发生了什么?

[英]How is this method reference a valid one ? What is happeneing behind the scenes?

I have a following program我有一个以下程序

import java.util.Scanner;

@FunctionalInterface
interface Retry {

    int run(Runnable action, int maxAttempts, long delayBeforeRetryMs);
}

final class RetryUtils {
    public static Retry retry= RetryUtils::retryAction; // assign the retryAction method to this variable

    private RetryUtils() { }

    public static int retryAction(
            Runnable action, int maxAttempts, long delayBeforeRetryMs) {

        int fails = 0;
        while (fails < maxAttempts) {
            try {
                action.run();
                return fails;
            } catch (Exception e) {
                System.out.println("Something goes wrong");
                fails++;
                try {
                    Thread.sleep(delayBeforeRetryMs);
                } catch (InterruptedException interruptedException) {
                    throw new RuntimeException(interruptedException);
                }
            }
        }
        return fails;
    }
}

class Retrying {
    private static final int MAX_ATTEMPTS = 10;
    private static final long DELAY_MS = 1;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        RetryUtils.retry.run(() -> System.out.println(scanner.nextLine()), MAX_ATTEMPTS, DELAY_MS);
    }
}

And I see the method retryAction returns int.我看到方法retryAction返回 int。 Then how is public static Retry retry= RetryUtils::retryAction;那么如何public static Retry retry= RetryUtils::retryAction; a valid assignment to object of type Retry ?对 Retry 类型的对象的有效分配? How does this compile ?这是如何编译的? Whats happening behind the scenes ?幕后发生了什么?

It is not a function call to expect int as a return type.期望 int 作为返回类型不是函数调用。 It is a lambda expression that kind of creates anonymous implementation of your Retry interface.它是一个 lambda 表达式,可以创建Retry接口的匿名实现。 It is almost equal to this几乎等于这个

 public static Retry retry= new Retry(){
     int run(Runnable action, int maxAttempts, long delayBeforeRetryMs)
     RetryUtils.this.retryAction(action,maxAttemps,delayBeforeRetryMs)
}

The analogy is almost accurate due to the statics and how lambda expression actually works, but you should get the idea.由于静态和 lambda 表达式的实际工作原理,这个类比几乎是准确的,但你应该明白这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM