为什么File :: isDirectory作为FileFilter工作正常? [英] Why File::isDirectory works fine as a FileFilter?

查看:120
本文介绍了为什么File :: isDirectory作为FileFilter工作正常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 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工作正常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆