Java中String方法的函数指针 [英] Function pointer to String method in Java
问题描述
我不了解lambda的一些事情。
I don't understand a couple of things with lambda.
String s = "Hello World";
Function<Integer, String> f = s::substring;
s = null;
System.out.println(f.apply(5));
为什么 f.apply
方法仍然存在在 s = null
时工作。毕竟,GC应该删除 String
对象,因为没有指向该对象的指针。
Why is the f.apply
method still working if s = null
. After all, the String
object should be deleted by the GC because there is no pointer that points to the object.
还有一件事,为什么我不需要这里的退货声明?
One more thing, why don't I need a return statement here?
Function<Integer, String> f = t -> t + "";
推荐答案
JLS,第15.13.3节描述了方法引用的运行时评估。
The JLS, Section 15.13.3 describes the runtime evaluation of method references.
方法参考表达式评估的时间比lambda表达式(第15.27.4节)更复杂。当方法引用表达式在:: separator之前具有表达式(而不是类型)时,将立即计算该子表达式。存储评估结果,直到调用相应功能接口类型的方法为止;此时,结果将用作调用的目标引用。这意味着:: separator前面的表达式仅在程序遇到方法引用表达式时计算,并且不会在函数接口类型的后续调用中重新计算。
The timing of method reference expression evaluation is more complex than that of lambda expressions (§15.27.4). When a method reference expression has an expression (rather than a type) preceding the :: separator, that subexpression is evaluated immediately. The result of evaluation is stored until the method of the corresponding functional interface type is invoked; at that point, the result is used as the target reference for the invocation. This means the expression preceding the :: separator is evaluated only when the program encounters the method reference expression, and is not re-evaluated on subsequent invocations on the functional interface type.
(大胆强调我的)
基本上是对 s的引用
因为它是方法参考被存储以供以后执行。这里,保存字符串Hello World
,以便稍后执行方法引用。因此,即使在声明方法引用之后,但在执行之前将 s
设置为 null
功能
,它仍然会使用字符串Hello World
。
Basically the reference to s
as it is for the method reference is stored for later execution. Here, the string "Hello World"
is saved for later execution of the method reference. Because of this, even if you set s
to null
after the declaration of the method reference, but before you execute the Function
, it will still use the string "Hello World"
.
将某些内容设置为 null
并不保证垃圾收集器会收集它,也不保证它会立即收集。
Setting something to null
does not guarantee that the garbage collector will collect it, and it won't guarantee that it's collected immediately.
此外,在这里,方法参考中仍然有一个引用,因此它不会在这里收集垃圾。
Also, here, there still is a reference in the method reference, so it won't get garbage collected at all here.
最后,lambda表达式主体有两种形式:一个表达式和一个带有(可能)一个return语句的语句块。使用
Finally, lambda expression bodies have 2 forms: an expression and a block of statements with (possibly) a return statement. With
Function<Integer, String> f = t -> t + "";
这是一个表达式。等效的块语句将是:
That is an expression. The block statement equivalent would be:
Function<Integer, String> f = t -> { return t + "";};
这篇关于Java中String方法的函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!