此程序为什么打印“ Hello”? (如何将函数指针转换为Java中的Runnable.run())

问题描述 投票:0回答:1

以下示例程序打印Hello。方法exampleMethod(Runnable toRun)具有Runnable类型参数。函数指针MyTest::sayHello没有运行方法。它是如何执行的?

public class MyTest {

    // Method that takes a "method" as argument
    static void exampleMethod(Runnable toRun) {
        toRun.run();
    }

    // Method to pass
    static void sayHello() {
        System.out.println("Hello");
    }


    public static void main(String[] args) throws Exception {
        exampleMethod(MyTest::sayHello);  // prints "Hello"
    }
}
java java-8
1个回答
0
投票

main方法内的代码与:

Runnable runnable = () -> {
MyTest.sayHello();
};

exampleMethod(runnable);
© www.soinside.com 2019 - 2024. All rights reserved.