功能接口和方法参考的行为 [英] Behavior of Functional Interface and Method Reference

查看:98
本文介绍了功能接口和方法参考的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当一个属于一个变量的方法的引用被销毁时会发生什么?

  public class嗨{
公共双人酒吧;

public Hey(){
bar = 2.0d;
}

public double square(double num){
return Math.pow(num,bar);
}
}

函数< Double,Double>广场;
whatsGonnaHappen:{
嘿hey = new Hey();
square = hey :: square;
} //是否仍然存在,因为它的方法正在被引用?

double ans = square.apply(23d);


解决方案

范围是一个编译时间概念,源代码可以使用。 来自JLS


声明的范围是声明中声明的实体
可以使用
简单名称引用的程序区域,只要它是可见的(第6.4.1节)。

名称 hey 限于的主体,whatsGonnaHappen 标记的语句与 hey 在运行时是垃圾收集的候选人(我认为是你担心的)。

关于变量捕获,是的,方法参考 hey :: square 是对特定对象(由 hey )引用的实例方法的引用,因此将捕获变量 hey 的值,当方法引用表达式被评估为产生一个实例并在调用 apply 时使用它。


What happens when the reference of a method which belongs to a variable is destroyed?

public class Hey{
    public double bar;

    public Hey(){
        bar = 2.0d;
    }

    public double square(double num){
        return Math.pow(num , bar);
    }
}

Function<Double, Double> square;
whatsGonnaHappen: {
    Hey hey = new Hey();
    square = hey::square;
}//is hey still kept around because its method is being referenced?

double ans = square.apply(23d);

解决方案

Scope is a compile time concept that governs where names in source code can be used. From the JLS

The scope of a declaration is the region of the program within which the entity declared by the declaration can be referred to using a simple name, provided it is visible (§6.4.1).

The fact that the name hey is restricted to the body of the whatsGonnaHappen labeled statement doesn't have any bearing on whether the instance referenced by hey at runtime is a candidate for garbage collection (which I assume is what you're worried about).

Concerning the variable capture, yes, the method reference hey::square is a reference to an instance method of a particular object (the one referenced by hey) and will therefore capture the value of the variable hey when the method reference expression is evaluated to produce an instance and use it when apply is invoked.

这篇关于功能接口和方法参考的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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