Search |
||
Garden thoughtPosted by forax on September 2, 2006 at 7:44 AM PDT
I'm seating in my garden, my laptop on my knees. i'm hearing the noise of some mowers in the background, my kid is sleeping, my wife is trying to resolve a sudoku, and i'm thinking about closure, again ! Why doesn't enable to define a closure using a reference to a method ?
public class HelloClosure {
public void sayHello(String name) {
System.out.println("hello "+name);
}
public static void main(String[] args) {
HelloClosure hello=new HelloClosure();
void(String) sayHello=hello.sayHello;
sayHello("closure");
}
}
The syntax seems obvious, the code (hello.sayHello)("closure")
is semantically equivalent to hello.sayHello("closure").
It's not very difficult to translate, the type of the closure is the type of the method, the referer of a non static method will be store in a field of the closure like any other local variable.
public static void main(String[] args) {
HelloClosure hello=new HelloClosure();
void(String) sayHello=void(String s) {
hello.sayHello(s);
};
sayHello("closure");
}
And by using the closure convertion, register an Actionlistener
on a button could become as simple as that:
public class Application {
public void onButtonAction(ActionEvent event) {
System.out.println("damn, i'm clicked");
}
public static void main(String[] args) {
Application application=new Application();
JButton button=new JButton("Ok !");
button.addActionListener(application.onButtonAction);
...
}
}
What do you think ? »
Related Topics >>
Open JDK Comments
Comments are listed in date ascending order (oldest first)
|
||
|
|