[英]Java 8 method reference usage example
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.我的问题是
FileFilter
接口只有一个抽象方法( boolean accept(File pathname)
),同时使用方法参考实现 accept 方法如何有效地使用File
class 中的boolean isHidden()
没有参数。 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.我了解到只有当参数与抽象方法匹配时我们才能应用方法引用,但这里的
accept
方法有一个File
类型的参数,但isHidden
没有参数。 Could you please explain how it is valid.你能解释一下它是如何有效的吗?
It's Lambda expression + method reference.它是 Lambda 表达式 + 方法参考。 What you mentioned about accept method is about Lambda expression, and what you mentioned about
File::isHidden
is method reference.你说的accept方法是Lambda表达式,你说的
File::isHidden
是方法引用。
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)可以变成:(Lamda表达式)
File[] hiddenFiles = new File(".").listFiles(file -> file.isHidden());
Then it can be turned into: (method reference)那么就可以变成:(方法参考)
File[] hiddenFiles = new File(".").listFiles(File::isHidden);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.