Consider below code,
interface TestInter {
public void abc();
}
class DemoStatic {
public static void testStatic(String abc) {
System.out.println(abc);
}
public void runTest () {
// Using lambda expression.
String str = "demo string" ;
TestInter demo1 = () -> DemoStatic.testStatic(str);
demo1.abc();
// Using method reference.
TestInter demo2 = DemoStatic::testStatic; // This line is not compiling.
demo2.abc();
}
}
We can invoke the testStatic
method as body of TestInter
interface's abc()
implementation if parameter of testStaic()
method will be eliminated as described in this so answer.
But in this case how can we write method reference for parameterized method testStatic
?
Your functional interface
TestInter
does not have corresponding signature for yourtestStatic(String)
method. If you want to refer totestStatic()
using the::
notation, you should add the parameter:According to Oracle Java tutorial, there are four kinds of method reference:
I prepared 3 interfaces - for 0, 1 and 2 parameters. Then we have 3 static and 3 instance methods:
Now look how each of the methods may be used as a method reference in various combinations, compare them with the previous table. See different method reference types in action and notice from where the parameters come.