空变量不会使方法引用无效

jg2*_*3 z 4 java nullpointerexception method-reference

NullPointerException当我使用方法引用绑定到dog后来分配null给变量的变量时,为什么代码没有抛出?

我正在使用Java 8。

import java.util.function.Function;

class Dog {
    private int food = 10;

    public int eat(int num) {
        System.out.println("eat " + num);
        this.food -= num;
        return this.food;
    }
}

public class MethodRefrenceDemo {

    public static void main(String[] args) {
        Dog dog = new Dog();
        Function<Integer, Integer> function = dog::eat;

        dog = null;

        // I can still use the method reference
        System.out.println("still have " + function.apply(2));
    }
}
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 6

dog::eat方法参考捕获实例通过引用dog,所以当你打电话function.apply(2)时,eat被该实例执行的方法。dog变量不再引用该实例并不重要。