A method reference is the shorthand syntax for a lambda expression that executes just ONE method.

Method reference is used to refer method of functional interface. For more information, visit Functional Interface in Java 8.

Double colon :: operator is used for method references. Here’s the general syntax of a method reference:

Object :: methodName

Method Reference in depth

1. A Static Method Reference

We use lambda expressions instead of using an anonymous class. But sometimes, the lambda expression is really just a call to any method, for example:

To make the code clearer, you can turn that lambda expression into a method reference:

Syntax Format
Lambda Expression Method Reference
(args) -> Class.staticMethod(args) Class::staticMethod
2. An Instance Method Reference of an Object of a Particular Type

An instance of an object is passed, and one of its methods is executed with some optional parameter(s).

In this example, we don’t pass any arguments to the method. The key point here is that an instance of the object is the parameter of the lambda expression, and we form the reference to the instance method with the type of the instance.

orderComputer method accepts a function to calculate Order Number and it will call generateOrderNumber method.

Syntax Format
Lambda Expression Method Reference
(obj, args) -> obj.instanceMethod(args) ObjectType::instanceMethod
3. An Instance Method Reference of an Existing Object

An instance defined somewhere else is used, and the arguments (if any) are passed behind the curtains like in the static method case.

Here in above example existing object of RepairStore is used to repair all the computers.

The key, in this case, is to use any object visible from an anonymous class/lambda expression and pass some arguments to an instance method of that object.

Syntax Format
Lambda Expression Method Reference
(args) -> obj.instanceMethod(args) obj::instanceMethod
4. Constructor Method Reference

The only thing this lambda expression does is to create a new object and we just reference a constructor of the class with the keyword new. Like in the other cases, the arguments (if any) are not passed in the method reference.

Most of the time, we can use this syntax with two (or three) interfaces of the java.util.function package.

If you have a constructor with three or more arguments, you would have to create your own functional interface.

Syntax Format
Lambda Expression Method Reference
(args) -> new ClassName(args) ClassName::new

Advantages of Method Reference

It is compact and easy-to-read lambda expressions.

We can avoid the one method restriction by grouping all your code in a static method, and create a reference to that method instead of using a class or a lambda expression with many lines.

Leave a Reply

Your email address will not be published. Required fields are marked *