Java 8方法引用默认方法实现

时间:2018-05-02 08:58:04

标签: java

 interface HelloWorld {
    String hello(String s);
}
public static void main(String[] args) {
        HelloWorld h = String::new;
        System.out.println(h.hello("dasdasdadasd"));
}

当我执行上面的方法时,它返回我在参数 dasdasdadasd 中传递的值 执行字符串类的哪种方法,或者是java在运行时提供的默认实现,还是默认情况下调用supplier.get()方法?

2 个答案:

答案 0 :(得分:5)

h被分配了对public String(String original)类的String构造函数的方法引用。这是唯一与String hello(String s)接口的HelloWorld方法签名匹配的构造函数。

因此h.hello("dasdasdadasd")创建一个新的String实例,其值等于"dasdasdadasd"并返回该实例。

HelloWorld h = String::new;

相当于:

HelloWorld h = s -> new String(s);

答案 1 :(得分:2)

您的代码可以重写为:

hw返回根据收到的字符串创建的字符串:

//Returns a string based on the input
HelloWorld hw = (s) -> {
    return new String(s);
}; 

在该对象上调用hello()将返回“基本上”输入:

//The value assigned to print is "dasdasdadasd", as returned by hw
String print = hw.hello("dasdasdadasd");

println正在接收dasdasdadasd

System.out.println(print); //"dasdasdadasd" is passed to println