Home > Software design >  Java 8 method reference usage example
Java 8 method reference usage example

Time:02-17

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

  • using Anonymous inner class implementation
    File[] hiddenFiles = new File(".").listFiles(new FileFilter() {
      public boolean accept(File file) {
        return file.isHidden();
      }
    });
  • using Method reference implementation
    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.

CodePudding user response:

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);

CodePudding user response:

See: https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html

Section:Kinds of Method References (Reference to an instance method of an arbitrary object of a particular type)

  • Related