I am going through an example which pulls an Array of hidden files from current directory related to method reference which is as mentioned below
File[] hiddenFiles = new File(".").listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isHidden();
}
});
File[] hiddenFiles = new File(".").listFiles(File::isHidden);
My question is FileFilter
interface has only one abstract method ( boolean accept(File pathname)
) while implementing accept method using method reference how it is valid to using boolean isHidden()
in File
class which has no parameters. I learnt that we can apply method reference only when parameters match with abstract method but here accept
method has a parameter of type File
but isHidden
has no parameters. Could you please explain how it is valid.
It's Lambda expression + method reference. What you mentioned about accept method is about Lambda expression, and what you mentioned about File::isHidden
is method reference.
They are 2 different things.
Your original one:
File[] hiddenFiles = new File(".").listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isHidden();
}
});
Can be turned into: (Lamda expression)
File[] hiddenFiles = new File(".").listFiles(file -> file.isHidden());
Then it can be turned into: (method reference)
File[] hiddenFiles = new File(".").listFiles(File::isHidden);
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.