繁体   English   中英

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

[英]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的数字。

请记住, 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

暂无
暂无

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

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