Java closure introduction
Can any one please describe this sort of co开发者_运维知识库de 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);
}
}
}
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:
public static <T> void sort(List<T> l, final {T, T=>Number} block) {
^^^^^^^^^^^^^^^^^^^^
An argument called block
which is of type "function that takes two T
and returns a Number
".
Collections.sort(l, new Comparator<T>() {
public int compare(T arg0, T arg1) {
...
}
}
}
An ordinary call to Collections.sort
with an instance of an anonymous subclass of Comparator
as second argument...
...
return block.invoke(arg0, arg1);
...
...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
interface Block<T> {
public int invoke(T arg1, T arg2);
}
class Test {
public static <T> void sort(List<T> l, final Block<T> block) {
Collections.sort(l, new Comparator<T>() {
public int compare(T arg0, T arg1) {
return block.invoke(arg0, arg1);
}
});
}
}
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.
精彩评论