java - 为什么这个程序打印“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"
}
}
解决方案
main 方法中的代码如下:
Runnable runnable = () -> {
MyTest.sayHello();
};
exampleMethod(runnable);
推荐阅读
- cairo - 如何正确构造简单的重复形状图案以用作开罗的填充?
- javascript - jsfiddle问题 - 保存为html时输出不正确显示
- delphi - 如何创建类似于 TeamViewer(隐藏/显示)的交互式选项面板?
- powershell - PowerShell 脚本未正确分配命名参数
- javascript - JavaScript:无法阻止函数运行 [井字游戏]
- c - 在 OpenSSL 库包含文件中找不到 i2c_ASN1_INTEGER 函数
- json - 在 XML 中存储原语
- angularjs - AngularJS - 带有轮播的 ng-repeat
- python - on_message 不会检测到任何消息
- jquery - 根据鼠标位置对 HTML 字符串中的单个字符进行样式设置