Why does the following not work?
import java.util.function.Function;
public class MethodRefTest {
public String passMeAround( String input ) {
return input + " been passed to me";
}
public Function<String, String> testReferences() {
final Function<String, String> f1 = MethodRefTest::passMeAround;
return f1;
}
public static void main( String[] args ) {
new MethodRefTest()
.testReferences()
.apply( "foo" );
}
}
Javac tells me:
MethodRefTest.java:14: error: invalid method reference
final Function<String, String> f1 = MethodRefTest::passMeAround;
^
non-static method passMeAround(String) cannot be referenced from a static context
1 error
I don't understand why the context is static. I read this but it does not seem to answer the problem at hand.
EDIT
Also according to oracle, "Reference to an instance method of an arbitrary object of a particular type" are possible via ContainingType::methodName
EDIT 2
@marko-topolnik helped me understand my mistake here.
Function<String, String> f1 = MethodRefTest::passMeAround;
refers to a static method String MethodRefTest.passMeAround(String)
BiFunction<MethodRefTest, String, String> f1 = MethodRefTest::passMeAround;
on the other hand, refers to the instance method of any instance
, that is passed in the apply clause.
BiFunction<MethodRefTest, String, String> f2 = MethodRefTest::passMeAround;
//call instance method
f2.apply(new MethodRefTest(), "some string");