[英]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.