功能接口和方法参考的行为 [英] Behavior of Functional Interface and Method Reference
问题描述
当一个属于一个变量的方法的引用被销毁时会发生什么?
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节)。
名称 关于变量捕获,是的,方法参考 What happens when the reference of a method which belongs to a variable is destroyed?
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 Concerning the variable capture, yes, the method reference 这篇关于功能接口和方法参考的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! hey
限于的主体,whatsGonnaHappen
标记的语句与 hey $ c引用的实例无关$ c>在运行时是垃圾收集的候选人(我认为是你担心的)。
hey :: square
是对特定对象(由 hey
)引用的实例方法的引用,因此将捕获变量 hey
的值,当方法引用表达式被评估为产生一个实例并在调用 apply
时使用它。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);
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).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.