简体   繁体   English

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

[英]Java Streams: Why can we pass non-static method references in map

I was wondering why we can pass method references even for methods that do not match the expected signature.我想知道为什么即使对于与预期签名不匹配的方法,我们也可以传递方法引用。 How does the JVM know that it should call the method of the instance passed, rather than calling the method with the passed instance as first parameter. JVM怎么知道应该调用传递的实例的方法,而不是调用传递的实例作为第一个参数的方法。 Here is an example of what I mean:这是我的意思的一个例子:

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);
    }
}

No void figures here.这里没有void的数字。

Remember that Person::getName method reference of Function doesn't mean a transformation from void to String but Person to String`.请记住, FunctionPerson::getName方法参考并不意味着从voidString的转换,而是从Person到 String`。

The map method requires a Function<T, R> where T is the original type ( Person in your case) and R stands for the transformation result type, which can be anything. map方法需要一个Function<T, R>其中T是原始类型(在您的情况下为Person ), R代表转换结果类型,可以是任何东西。

Notice the method public String getName() has String as the return type which is inferred into R and the parameter of the map method becomes Function<Person, String> regardless whether it is written as person -> person.getName() or Person::getName .请注意方法public String getName()String作为返回类型,它被推断为R并且map方法的参数变为Function<Person, String>无论它是写成person -> person.getName()还是Person::getName They both mean the same.他们两个意思是一样的。

Again, there is no void figuring.同样,没有void

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

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