空变量不会使方法引用无效 [英] Nulling variable does not invalidate method reference

查看:80
本文介绍了空变量不会使方法引用无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why does the code not throw a NullPointerException when I use a method reference tied to a variable dog which I later assigned null to?

我使用的是 Java 8.

I am using 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));
    }
}

推荐答案

dog::eat 方法引用捕获了 dog 引用的实例,所以当你调用 function.apply(2),为该实例执行 eat 方法.dog 变量不再引用该实例并不重要.

The dog::eat method reference captures the instance referenced by dog, so when you call function.apply(2), the eat method is executed for that instance. It doesn't matter that the dog variable no longer references that instance.

这篇关于空变量不会使方法引用无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆