3

I am having some confusion of how method references work in Java 8. I wrote the following code segment for filtering hidden files in a folder. They are producing correct result. I am not understanding -> how method signature of listFiles method is working for option 2 of this code segment.

This is what I found in Java 8 documentation

  1. File[] listFiles()
  2. File[] listFiles(FileFilter filter)
  3. File[] listFiles(FilenameFilter filter)
File[] hidden = f.listFiles((p)-> p.isHidden()); //Option 1 - function signature matching (based on my understanding)
for (int i = 0; i < hidden.length; i++) {
    System.out.println(hidden[i]);
}
System.out.println("================================");
File[] hidden1 = f.listFiles(File::isHidden); //Option 2 - how this method call is working
for (int i = 0; i < hidden1.length; i++) {
    System.out.println(hidden1[i]);
}
0

1 Answer 1

2

What is a method refernce

You can see a method reference as a lambda expression, that call an existing method.

Kinds of method references

There are four kinds of method references:

  • Reference to a static method: ContainingClass::staticMethodName
  • Reference to an instance method of a particular object: containingObject::instanceMethodName
  • Reference to an instance method of an arbitrary object of a particular type: ContainingType::methodName
  • Reference to a constructor: ClassName::new

How to understand it?

The following expression that lists all hidden files: f.listFiles(p -> p.isHidden());

This expression is composed by the instance method listFiles(FileFilter) and your lambda expression p -> p.isHidden() that is not a anonymous method but an existing instance method of the class File.

Note that FileFilter is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference. Hence, you can write your expression f.listFiles(File::isHidden);

Side notes

  1. You don't need the parentheses surrounding the p. For a better readibility, I would suggest to replace (p) with simply a p. Hence, your lambda expression will become p-> p.isHidden().
  2. Your for loop can be replaced by an enhanced for loop:
for (File value : hidden) {
   System.out.println(value);
}

Documentation:

Method reference

FileFilter

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.