小编ada*_*rod的帖子

有没有办法在jshell中为顶级函数使用方法引用?

假设我在jshell中这样做:

jshell> void printIsEven(int i) {
   ...>     System.out.println(i % 2 == 0);
   ...> }
|  created method printIsEven(int)

jshell> List<Integer> l = Arrays.asList(7,5,4,8,5,9);
l ==> [7, 5, 4, 8, 5, 9]

jshell> l.forEach(/* ??? */); // is it possible to use a method reference here?
Run Code Online (Sandbox Code Playgroud)

在普通程序中,我可以l.forEach(this::printIsEven)在非静态上下文中或l.forEach(MyClass::printIsEven)在名为的类的静态上下文中编写MyClass.

this::printIsEven在jshell中使用不起作用,因为jshell在静态上下文中执行语句,但是你不能使用静态方法引用,因为没有类名称来加前缀::printIsEven,而尝试l.forEach(::printIsEven)只是一个语法错误.

java method-reference java-9 jshell

12
推荐指数
1
解决办法
468
查看次数

标签 统计

java ×1

java-9 ×1

jshell ×1

method-reference ×1