Ski*_*kip 11 java-8 method-reference
有人可以向我解释,
为什么传递非静态方法引用方法File::isHidden是可以的,
但是将方法引用传递给非静态方法MyCass::mymethod- 给我一个
"不能对非静态方法进行静态引用"?
public static void main(String[] args) {
File[] files = new File("C:").listFiles(File::isHidden); // OK
test(MyCass::mymethod); // Cannot make a static reference to the non-static method
}
static interface FunctionalInterface{
boolean function(String file);
}
class MyCass{
boolean mymethod(String input){
return true;
}
}
// HELPER
public static void test(FunctionalInterface functionalInterface){}
Run Code Online (Sandbox Code Playgroud)
Pet*_*ser 11
对非静态方法的方法引用需要一个实例来操作.
在listFiles方法的情况下,参数是FileFilterwith accept(File file).在操作实例(参数)时,可以引用其实例方法:
listFiles(File::isHidden)
Run Code Online (Sandbox Code Playgroud)
这是简写
listFiles(f -> f.isHidden())
Run Code Online (Sandbox Code Playgroud)
现在为什么不能使用test(MyCass::mymethod)?因为您根本没有MyCass要操作的实例.
但是,您可以创建一个实例,然后将方法引用传递给您的实例方法:
MyCass myCass = new MyCass(); // the instance
test(myCass::mymethod); // pass a non-static method reference
Run Code Online (Sandbox Code Playgroud)
要么
test(new MyCass()::mymethod);
Run Code Online (Sandbox Code Playgroud)