以下示例程序打印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"
}
}
main方法内的代码与:
Runnable runnable = () -> {
MyTest.sayHello();
};
exampleMethod(runnable);