方法参考。无法对非静态方法进行静态引用 [英] Method Reference. Cannot make a static reference to the non-static method

查看:379
本文介绍了方法参考。无法对非静态方法进行静态引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以向我解释,

为什么将非静态方法引用传递给方法 File :: isHidden 是好的,

但是将方法引用传递给非静态方法 MyCass :: mymethod - 给我一个
无法对该方法进行静态引用非静态方法

Can someone explain to me,
why passing a non-static method-reference to method File::isHidden is ok,
but passing method reference to a non-static method MyCass::mymethod - gives me a "Cannot make a static reference to the non-static method" ?

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){}


推荐答案

对非静态方法的方法引用需要操作实例。

对于 listFiles 方法,参数为 FileFilter 接受(文件文件)。在对实例(参数)进行操作时,可以引用其实例方法:

In the case of the listFiles method, the argument is a FileFilter with accept(File file). As you operate on an instance (the argument), you can refer to its instance methods:

listFiles(File::isHidden)

这是

listFiles(f -> f.isHidden())

现在为什么你不能使用 test(MyCass :: mymethod)?因为你根本没有 MyCass 的实例来操作。

Now why can't you use test(MyCass::mymethod)? Because you simply don't have an instance of MyCass to operate on.

但是你可以创建一个实例,然后将方法引用传递给您的实例方法:

You can however create an instance, and then pass a method reference to your instance method:

MyCass myCass = new MyCass(); // the instance
test(myCass::mymethod); // pass a non-static method reference

test(new MyCass()::mymethod);

这篇关于方法参考。无法对非静态方法进行静态引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆