为什么代码不抛出NullPointerException
当我使用与变量绑定的方法引用时dog
我后来分配了null
to?
我正在使用 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));
}
}
The dog::eat
方法引用捕获引用的实例dog
,所以当你打电话时function.apply(2)
, the eat
方法针对该实例执行。没关系dog
变量不再引用该实例。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)