java - java 8中的功能接口如何工作
问题描述
这是我在研究功能接口概念时遇到的一个示例。
interface Sayable{
void say();
}
public class MethodReference {
public static void saySomething(){
System.out.println("Hello, this is static method.");
}
public static void main(String[] args) {
// Referring static method
Sayable sayable = MethodReference::saySomething;
// Calling interface method
sayable.say();
}
}
这是打印“你好,这是静态方法”。在运行时输出。我的问题是当我们调用 say() 方法时它是如何打印输出的(未实现)
解决方案
你可以这样想方法引用:
Sayable sayable = new Sayable() {
@Override
void say() {
// Grab the body of the method referenced by the method reference,
// which is the following:
System.out.println("Hello, this is static method.");
}
}
方法引用是有效的,因为
- 目标类型是功能接口
Sayable
(您试图将结果存储到Sayable
类型中);和 - 方法引用的签名
saySomething()
匹配功能接口方法say()
,即参数和返回类型匹配1。
被称为变量say()
的实例的方法的实现等于方法引用所引用的方法的主体。Sayable
sayable
所以就像 JB Nizet 在评论中所说的那样,say()
实际上已经实现了。
1一个小细节:“匹配”这个词并不完全意味着“相等”。例如,如果saySomething()
返回一个int
,它仍然可以工作,尽管目标类型的唯一方法将返回类型定义为void
。
推荐阅读
- c++ - 仅在一个变量中拆分全名的单词
- sql - 在excel中对两个字段求和
- c# - 在 Xamarin Visual Studio 2017 中使用 Soap 客户端 - 都柏林总线实时信息
- java - Java 自定义注解采用另一个注解
- python - 将 django 表外键与过滤功能匹配
- python - valueerror:无法将大小为 315 的数组重新整形为形状 (32,32)
- kotlin - 如何在我的内部类中使用变量?
- autodesk-forge - 创建 WorkItem 失败并显示“对象引用未设置为对象的实例”。
- python - 根据列条件删除相等数量的行
- c++ - std::tie 上的 std::invoke_result