为什么以下不起作用?
import java.util.function.Function;
public class MethodRefTest {
public String passMeAround( String input ) {
return input + " been passed to me";
}
public Function testReferences() {
final Function f1 = MethodRefTest::passMeAround;
return f1;
}
public static void main( String[] args ) {
new MethodRefTest()
.testReferences()
.apply( "foo" );
}
}
Javac告诉我:
MethodRefTest.java:14: error: invalid method reference
final Function f1 = MethodRefTest::passMeAround;
^
non-static method passMeAround(String) cannot be referenced from a static context
1 error
我不明白为什么上下文是静态的.我读了this,但它似乎没有解决手头的问题.
编辑
同样根据oracle,可以通过ContainingType :: methodName“引用特定类型的任意对象的实例方法”.
编辑2
@ marko-topolnik帮我理解了我的错误.
函数< String,String> f1 = MethodRefTest :: passMeAround;
指一个静态方法String MethodRefTest.passMeAround(String)
BiFunction f1 = MethodRefTest::passMeAround;
另一方面,指的是在apply子句中传递的任何实例的实例方法.
BiFunction f2 = MethodRefTest::passMeAround;
//call instance method
f2.apply(new MethodRefTest(), "some string");