Skip to content
thesarfo

Concept

Method References

Referencing static and instance methods directly with the :: operator instead of writing a lambda wrapper.

views 0

If you have a functional interface, you can reference a matching method directly when creating an instance of that interface.

interface MyLambda {
public void display(String str);
}
public class LambdaDemo {
public static void reverse(String str) {
StringBuffer sb = new StringBuffer(str);
sb.reverse();
System.out.println(sb);
}
public static void main(String[] args) {
MyLambda mlb = System.out::println;
MyLambda ml = LambdaDemo::reverse;
mlb.display("Hello");
ml.display("Hello");
}
}

Looking at System.out::println — the static method println, after the ::, is assigned to the display method of the functional interface above. So calling .display() automatically prints the string passed to it. Same thing with the static reverse method: calling display on ml calls reverse() and prints its result.

But what if the method isn’t static? You can’t reference it directly against the class. Instead, create an instance of the class first, and reference the method through that object rather than the class name.

interface MyLambda {
public void display(String str);
}
public class LambdaDemo {
public void reverse(String str) {
StringBuffer sb = new StringBuffer(str);
sb.reverse();
System.out.println(sb);
}
public static void main(String[] args) {
LambdaDemo ld = new LambdaDemo(); // instance of the class
MyLambda ml = ld::reverse; // referencing the "ld" object instead of the class
ml.display("Hello");
}
}