Method reference in Java 8

/, Java 8/Method reference in Java 8

What is method reference ?

To create lambda expressions we use anonymous methods. Some times the implementation that you want to create in lambda is already available in existing method. In those cases method references enable you to refer functional interface method by name in place of lambda expressions.

Our specified method can be either static method or instance method. Functional interface method and our specified method should have same argument and compatible return types, except this remaining things like method name, modifiers are not required to match.

Types of method references :

  1. Reference to static method.
  2. Reference to an instance method of a particular object.
  3. Reference to an instance method of an arbitrary object of a particular type

To define method reference we have to use :: (double colon) operator.

1.Reference to static method

You can refer to static method defined in the class. Following is the syntax and example which describe the process of referring static method in Java.

Syntax:

Example with lambda expression :

Same example with method reference :

2.Reference to an instance method

Like static methods, you can refer instance methods also. In the following example, we are describing the process of referring the instance method.

Syntax:

Reference to instance method example

3.Reference to an instance method of an arbitrary object of a particular type

Like static methods, you can refer instance methods also. In the following example, we are describing the process of referring the instance method.

Syntax:

 

This type of method references are little confusing. If you look into the example String::toUpperCase, usually toUpperCase() method is called on a string reference but we have written class name “String” as like it is a static method. When we use method references they also go through similar checks as lambda expression goes. Compiler will try to match the method reference with any of functional descriptor syntax and if matches then passes on.

Example

Leave a Reply