简体   繁体   English

FileFilter Java 8的方法参考

[英]Method reference for FileFilter Java 8

I have the following code for the FileFilter : 我有FileFilter的以下代码:

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

I want to write this with a method reference. 我想用方法参考写这个。 This was my first try: 这是我的第一次尝试:

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

This gives me an error: 这给了我一个错误:

incompatible Types: invalid method reference. 不兼容的类型:无效的方法引用。

It works if I try this with an lambda expression like: 如果我尝试使用lambda表达式,它可以工作:

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

How must I change my code to get the method reference to work? 我如何更改代码以使方法引用工作?

You need to use 你需要使用

final FileFilter directoryFilter = File::isDirectory;

This method reference is exactly the same as the lambda expression pathname -> pathname.isDirectory() that you wrote. 方法引用与您编写的lambda表达式pathname -> pathname.isDirectory()完全相同。

Method references with the syntax ContainingType::methodName are used to reference to an instance method of an arbitrary object of the ContainingType type. 使用语法ContainingType::methodName方法引用用于引用ContainingType类型的任意对象的实例方法。

The method reference test::isDirectory would actually refer to the instance method isDirectory on the specific test instance (not for an arbitrary File instance). 方法引用test::isDirectory实际上是指特定test实例上的实例方法isDirectory (不适用于任意File实例)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM