小编jg2*_*3 z的帖子

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

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)

java nullpointerexception method-reference

4
推荐指数
1
解决办法
106
查看次数