假设我在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)只是一个语法错误.