简体   繁体   English

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

[英]Java 8 Method references default method implementation

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

When I execute the above method,it returns the value which I am passing in the arguments dasdasdadasd Which method of string class is executed or is there any default implementation which java provides at runtime or by default it calls supplier.get() method? 当我执行上面的方法时,它返回我在参数dasdasdadasd中传递的值。执行字符串类的哪个方法,或者是java在运行时提供的默认实现,或者默认情况下它调用supplier.get()方法?

h was assigned a method reference to the public String(String original) constructor of the String class. h被赋予对String类的public String(String original)构造函数的方法引用。 That's the only constructor that matches the signature of the String hello(String s) method of your HelloWorld interface. 这是唯一与HelloWorld接口的String hello(String s)方法的签名匹配的构造函数。

Therefore h.hello("dasdasdadasd") creates a new String instance whose value is equal to "dasdasdadasd" and returns that instance. 因此, h.hello("dasdasdadasd")创建一个新的String实例,其值等于"dasdasdadasd"并返回该实例。

HelloWorld h = String::new;

is equivalent to: 相当于:

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

Your code can be rewritten as: 您的代码可以重写为:

hw returns a string created from what it receives: hw返回从它收到的内容创建的字符串:

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

Invoking hello() on that object returns "basically" the input: 在该对象上调用hello()会返回“基本上”输入:

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

println Is receiving dasdasdadasd : println正在接收dasdasdadasd

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM