开发者

How are the interfaces going to be replaced/augmented by the closures in Java?

Java 7 will have closures ( finally ), and I wonder how the existing code using single method classes/interfaces ( like Runnable, Comparator, etc ) will be used now.

Would that code be replaced? Will be a conversion of some sort? An extra method using the closure will be added?

Does anyone knows how is this going to work/what the plans are?

For instance, to use the FileFilter today we do:

....
File [] files = directory.listFiles( new FileFilter() 
                      public boolean accept( File file ) {
                          return file.getName().endsWith(".java");
                       }
                   });

Does anyone knows how is this going to work on Java7?

Maybe overloading the method File.listFiles to receive a closure?

File [] files = directory.listFiles(#(File file){
            开发者_StackOverflow社区        return file.getName().endsWith(".java");
                 });


These classes/interfaces are called SAM (Single Abstract Method) types, and conversion of lambdas to SAM types is a central part of the project lambda proposal for JDK7. In fact, the most recent iteration of the proposal removes function types and only allows lambdas as instances of SAM types. With the latest version of the syntax (which is not final), your example could be written like:

File[] files = directory.listFiles(#(file){file.getName().endsWith(".java")});

With listFiles(FileFilter) unchanged from what it is now.

You could also write

FileFilter javaFileFilter = {#(file){file.getName().endsWith(".java")};

You may also want to take a look at this State of the Lambda document which is the latest update to the proposal and explains things in more detail. Note also that the specifics are all subject to change, though it's pretty certain that a lambda expression/block will be usable as a SAM type like I've described.


Existing code isn't affected and won't need replacing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜