首页 > 解决方案 > 为什么这个程序打印“Hello”?(如何将函数指针转换为 Java 中的 Runnable.run())

问题描述

下面的示例程序打印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"
    }
}

标签: javajava-8

解决方案


main 方法中的代码如下:

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

exampleMethod(runnable);

推荐阅读