简体   繁体   中英

Method references of listFiles

I have once read the following code from a book about method references.

File[] hiddenFiles = new File(".").listFiles(File::isHidden)

When I look up from the File API for the listFiles method, I see it only has the following methods:

listFiles(FileFilter filter)

listFiles(FilenameFilter filter)

I have tried the code and it works. But while the API states it accepts either FileFilter or FilenameFilter , why the code can work ?

My understanding of File::isHidden is that it is equivalent to the following lambdas:

(File file) -> file.isHidden()

But in FileFilter, the method that need to specify is following.

boolean accept(File pathname)

Then shouldn't there be a method named accept defined there, like:

File[] hiddenFiles = new File(".").listFiles(new FileFilter() {
 public boolean accept(File file) {
   return file.isHidden();
 }
});

Or the compiler can somehow automatically detect the pattern and regard the code as a FileFilter, although the method "accept" is not defined and a FileFilter object is not created ?

There are actually several interesting parts to this question:

  • Q: What is isHidden , and why is it a permissible argument to File.listFiles()?

    https://www.geeksforgeeks.org/file-ishidden-method-in-java-with-examples

    The isHidden() function is a part of File class in Java . This function determines whether the is a file or Directory denoted by the abstract filename is Hidden or not.The function returns true if the abstract file path is Hidden else return false.

  • Q: What is the File::isHidden syntax?

    The "double colon" is a method reference . It's new with Java 8 and higher.

  • Q: So why is isHidden() an acceptable FileFilter parameter?

    https://docs.oracle.com/javase/8/docs/api/java/io/FileFilter.html

    This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

    File::isHidden is a lambda expression that returns "true" or "false".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM