更新时间:2023-10-05 14:31:28
对非静态方法的方法引用需要操作实例。
对于 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);