Java闭包介绍
谁能描述一下这种代码来理解 Java 闭包。
public static <T> void sort(List<T> l, final {T, T=>Number} block) {
Collections.sort(l, new Comparator<T>() {
public int compare(T arg0, T arg1) {
return block.invoke(arg0, arg1);
}
}
}
Can any one please describe this sort of code to understand Java closure.
public static <T> void sort(List<T> l, final {T, T=>Number} block) {
Collections.sort(l, new Comparator<T>() {
public int compare(T arg0, T arg1) {
return block.invoke(arg0, arg1);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
重要说明:问题是关于之前的提案。这不是所选择的语法。将此问答视为“历史参考”。
Gilad Bracha、Neal Gafter、James Gosling 和 Peter von der Ahé 的 BGGA-proposal 中描述了此语法。
这段代码可以描述如下:
它采用一个函数作为第二个参数,该函数接受参数
(T, T)
并返回Number
(并将其分配给参数block
)然后它创建一个
Comparator
。它通过将compare
方法委托给对block
的调用来实现该方法。将此比较器传递给
Collections.sort
方法。下面是语法的细分:
一个名为
block
的参数,其类型为“函数,需要两个T
并返回一个Number”。
对
Collections.sort
的普通调用,使用Comparator
的匿名子类的实例作为第二个参数......返回由定义的函数计算的数字
块
参数。就经典 Java 而言,您的代码片段将对应于类似的内容
Important note: The question was regarding an earlier proposal. This was not the syntax chosen. See this Q/A as a "historical reference".
This syntax is described in the BGGA-proposal by Gilad Bracha, Neal Gafter, James Gosling, and Peter von der Ahé.
This snippet of code can be described as follows:
It takes as the second argument a function taking parameters
(T, T)
and returningNumber
(and assigns it to parameterblock
)It then creates a
Comparator<T>
out of it. This it does by implementing thecompare
method by delegating it to a call toblock
.Passes this comparator to the
Collections.sort
method.Here comes a break down of the syntax:
An argument called
block
which is of type "function that takes twoT
and returns aNumber
".An ordinary call to
Collections.sort
with an instance of an anonymous subclass ofComparator
as second argument......which returns the number computed by the function defined by the
block
argument.Put in terms of classical Java, your snippet would correspond to something like
正如 @axtavt 指出的那样,Java 7(不幸的是)不会有闭包。然而,Groovy 确实如此,它在 JVM 上运行,并且与其他 Java 代码集成得非常好。我会阅读此内容以获取更多信息。
As @axtavt points out, Java 7 is (unfortunately) not going to have closures. However, Groovy does, runs on the JVM, and integrates very nicely with other Java code. I'd read this for more information.