Method Reference for FileFilter Java 8

I have the following code for FileFilter:

final FileFilter directoryFilter = new FileFilter()
    @Override
    public boolean accept(final File pathname)
    {
        return pathname.isDirectory();
    }
};

I want to write this using a method reference. This was my first attempt:

final File test;
final FileFilter directoryFilter = test::isDirectory;

This gives me an error:

incompatible types: invalid method reference.

This works if I try this with a lambda expression:

final FileFilter directoryFilter = pathname -> pathname.isDirectory()

How do I change my code to get a link to a method?

+4
source share
1 answer

You need to use

final FileFilter directoryFilter = File::isDirectory;

This link is exactly the same as your lambda expression pathname -> pathname.isDirectory().

ContainingType::methodNameMethod references with syntax are used to refer to an instance method of an arbitrary type object ContainingType.

test::isDirectory isDirectory test ( File).

+6

Source: https://habr.com/ru/post/1615616/


All Articles