方法参考.无法对非静态方法进行静态引用

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)

  • 您无法从“static”方法(例如“main”)中实例化“MyClass”,因为它是一个_非静态_内部类。您必须将该类声明为静态。我假设原始示例中的代码包装在一个类中。 (2认同)