首页 > 解决方案 > 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() 方法时它是如何打印输出的(未实现)

标签: javajava-8functional-interface

解决方案


你可以这样想方法引用:

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()的实例的方法的实现等于方法引用所引用的方法的主体。Sayablesayable

所以就像 JB Nizet 在评论中所说的那样,say()实际上已经实现了。


1一个小细节:“匹配”这个词并不完全意味着“相等”。例如,如果saySomething()返回一个int,它仍然可以工作,尽管目标类型的唯一方法将返回类型定义为void


推荐阅读