问题描述
为什么 File :: isDirectory 在以下示例中作为FileFilter正常工作?
Why File::isDirectory works fine as a FileFilter in the below example?
File[] files = new File(".").listFiles(File::isDirectory);
listFiles方法需要FileFilter作为参数
The listFiles method requires a FileFilter as a parameter
public File[] listFiles(FileFilter filter) {
...
}
FileFilter是一个功能接口,它有一个方法 accept ,带有File参数
The FileFilter is a functional interface which has one method accept with a File parameter
boolean accept(File pathname);
File类中的isDirectory方法没有参数
And isDirectory method from the File class has no parameters
public boolean isDirectory() {
...
}
推荐答案
为了使事情更清楚,方法引用 File :: isDirectory
等同于以下lambda :
To make things clearer the method reference File::isDirectory
is equivalent to the following lambda:
file -> file.isDirectory()
如你所见我们传递的是文件
参数然后在它上面调用 isDirectory
返回 boolean
因此满足 FileFilter
界面中的SAM。
As you can see we're passing a File
parameter then calling isDirectory
upon it which returns boolean
hence satisfies the SAM in the FileFilter
interface.
这篇关于为什么File :: isDirectory作为FileFilter工作正常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!