Java 中的闭包将如何替换/增强接口?
Java 7 将有闭包(finally),我想知道现在如何使用使用单一方法类/接口(如 Runnable、Comparator 等)的现有代码。
那个代码会被替换吗?会是某种转换吗?会添加一个使用闭包的额外方法吗?
有谁知道这将如何运作/计划是什么?
例如,今天我们要使用 FileFilter:
....
File [] files = directory.listFiles( new FileFilter()
public boolean accept( File file ) {
return file.getName().endsWith(".java");
}
});
有谁知道这在 Java7 上如何工作?
也许重载方法 File.listFiles 来接收闭包?
File [] files = directory.listFiles(#(File file){
return file.getName().endsWith(".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){
return file.getName().endsWith(".java");
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这些类/接口称为 SAM(单一抽象方法)类型,将 lambda 转换为 SAM 类型是 JDK7 项目 lambda 提案的核心部分。事实上,该提案的最新迭代删除了函数类型,并且仅允许 lambda 作为 SAM 类型的实例。使用最新版本的语法(不是最终版本),您的示例可以这样编写:
listFiles(FileFilter)
与现在保持不变。您也可以写
您可能还想看看这个 Lambda 文档的状态,这是提案的最新更新,并更详细地解释了事情。另请注意,尽管 lambda 表达式/块可以像我所描述的那样用作 SAM 类型,但细节可能会发生变化。
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:
With
listFiles(FileFilter)
unchanged from what it is now.You could also write
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.