为什么File :: isDirectory作为FileFilter工作正常?

为什么File :: isDirectory在下面的例子中作为FileFilter正常工作?

File[] files = new File(".").listFiles(File::isDirectory); 

listFiles方法需要FileFilter作为参数

 public File[] listFiles(FileFilter filter) { ... } 

FileFilter是一个function接口,它有一个方法接受 File参数

 boolean accept(File pathname); 

而且File类中的isDirectory方法没有参数

 public boolean isDirectory() { ... } 

为了使事情更清楚,方法引用File::isDirectory等效于以下lambda:

 file -> file.isDirectory() 

正如您所看到的那样, 我们传递一个File参数,然后调用isDirectory ,返回boolean从而满足FileFilter接口中的SAM。

因为FileFilter是@FunctionalInterface 。 它只有一个方法,它接受一个文件作为参数并返回一个布尔值。

 @FunctionalInterface public interface FileFilter { /** * Tests whether or not the specified abstract pathname should be * included in a pathname list. * * @param pathname The abstract pathname to be tested * @return true if and only if pathname * should be included */ boolean accept(File pathname); } 

如果要扩展此方法引用并使用Anonymous类编写它。 它看起来像这样

 File[] files = new File(".").listFiles(new FileFilter() { @Override public boolean accept(File file) { return file.isDirectory(); } }); 

这是自我解释的。 希望很清楚。