Do you know "#"? Let me guess, not too familiar. Because in the Java1.4.2 era, "#" is used only in writing the annotated content of Javadoc, to link (@see) to the corresponding class of concrete methods. In addition, we almost never use it when writing code.
However, don't be surprised, after the Java 7 release, "#" may become the most familiar friend of Java programmers! Because a few days ago (Edit note: This translation at the end of November 09, when Sun just announced that Java 7 will contain simple closures), Sun Java Mark Reinhold, chief engineer of SE and OPENJDK, has just announced that Java 7 will add a simplified version of the "Closure" feature, where the key symbol is "#". For this reason, the official release time for Java 7 will be postponed from February 2010 to September.
In Java 7, "#" will let the function method become a first-class citizen of the Java language. Let's look at how to implement the closure with the # syntax:
Simple Method Reference Example:
For example, to refer to the Equals method of the string class, you should write this:
String#equals (Object)
Look at one more example:
Java.io.file#exists ()
Event Listener 1 (code example, from Cay Horstmann)
Before using closures:
Button.addactionlistener (
New ActionListener () {
public void actionperformed (ActionEvent) {
System.out.println ("hi!"); }
}
);
After using closures:
Button.addactionlistener (# (ActionEvent e) System.out.println ("hi!)");
Event Listener 2 (code example, from FSM)
Before using closures:
public void init () {
JButton button = ...;
Button.addactionlistener (new ActionListener () {
public void actionperformed (ActionEvent ev) {
Handleaction (EV);
}
});
}
public void handleaction (ActionEvent ev) {
Handle Event
}
After using closures:
After using closures:
public void init () {
JButton button = ...;
Button.addactionlistener (This#handleaction (ActionEvent));
}
public void handleaction (ActionEvent ev) {
Handle Event
}