[英]Java Streams: Why can we pass non-static method references in map
我想知道為什么即使對於與預期簽名不匹配的方法,我們也可以傳遞方法引用。 JVM怎么知道應該調用傳遞的實例的方法,而不是調用傳遞的實例作為第一個參數的方法。 這是我的意思的一個例子:
class Person {
String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
public class Main {
public static void main(String[] args) {
List<Person> listOfPeople = new ArrayList<>();
listOfPeople.add(new Person("Mike"));
listOfPeople.add(new Person("Tom"));
// this makes perfect sense, since we pass a lambda with the signature Person -> String
listOfPeople.stream().map(person -> person.getName()).forEach(System.out::println);
// I know that this works but I don't understand why, the method passed has signature void -> String but java somehow knows to resolve it like on top.
listOfPeople.stream().map(Person::getName).forEach(System.out::println);
}
}
這里沒有void
的數字。
請記住, Function
的Person::getName
方法參考並不意味着從void
到String
的轉換,而是從Person
到 String`。
map
方法需要一個Function<T, R>
其中T
是原始類型(在您的情況下為Person
), R
代表轉換結果類型,可以是任何東西。
請注意方法public String getName()
有String
作為返回類型,它被推斷為R
並且map
方法的參數變為Function<Person, String>
無論它是寫成person -> person.getName()
還是Person::getName
。 他們兩個意思是一樣的。
同樣,沒有void
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.