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 ?
Method references are a special type of lambda expressions. They're often used to create simple lambda expressions by referencing existing methods. There are four kinds of method references: Static methods. Instance methods of particular objects.
Types of Method ReferencesStatic Method Reference. Instance Method Reference of a particular object. Instance Method Reference of an arbitrary object of a particular type. Constructor Reference.
listFiles() returns the array of abstract pathnames defining the files in the directory denoted by this abstract pathname.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With