为什么当我使用绑定到变量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));
}
}
答案 0 :(得分:6)
dog::eat
方法引用捕获dog
引用的实例,因此,当您调用function.apply(2)
时,将对该实例执行eat
方法。没关系,dog
变量不再引用该实例。
答案 1 :(得分:1)
在lambda表达式上使用的变量dog
仅在lambda表达式的范围内可见,因为它的定义和使dog
无效不会影响方法引用{ {1}}。
不使用具有相同功能的dog::eat
的示例:
dog