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

时间:2019-06-05 09:11:14

标签: 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));
    }
}

2 个答案:

答案 0 :(得分:6)

dog::eat方法引用捕获dog引用的实例,因此,当您调用function.apply(2)时,将对该实例执行eat方法。没关系,dog变量不再引用该实例。

答案 1 :(得分:1)

在lambda表达式上使用的变量dog仅在lambda表达式的范围内可见,因为它的定义和使dog无效不会影响方法引用{ {1}}。

不使用具有相同功能的dog::eat的示例:

dog