Java Streams:为什么我们可以在映射中传递非静态方法引用



我想知道为什么即使对于与预期签名不匹配的方法,我们也可以传递方法引用。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数字

请记住,FunctionPerson::getName方法引用并不意味着从voidString的转换,而是意味着Person到String`的转换。

map方法需要一个Function<T, R>,其中T是原始类型(在您的情况下是Person(,R代表转换结果类型,可以是任何类型。

注意,方法public String getName()具有String作为返回类型,该返回类型被推断为R,并且map方法的参数变为Function<Person, String>,而不管它是被写为person -> person.getName()还是Person::getName。它们的意思都一样。

同样,没有void配置。

最新更新