Home Post Core Java

Method Reference in Java (Instance, Static, and Constructor Reference)

Mar 31, 2024

Method references are compact, easy-to-read lambda expressions for methods that already have a name.

Sometimes, a lambda expression does nothing but call an existing method. In those cases, it's often clearer to refer to the existing method by name.

There are four kinds of method references: bound, unbound, static, and constructor.

1) Bound Method References

A "bound method reference" refers to an instance method that's bound to a receiver object; its syntax is: containingObject::instanceMethodName.

2) Unbound Method References

An "unbound method reference" refers to an instance method that's not bound to a receiver object; its syntax is: ContainingType::methodName.

However, because an instance method still requires a receiver object, the receiver object is created by the JVM.

3) Constructor References

You can use a method reference to refer to a constructor without instantiating the named class; its syntax is: ClassName::new.

Constructor References with multiple parameters

For constructors with more than two parameters we need to create your own Functional Interfaces:

4) Static Method References

A "static method reference" refers to a static method in a specific class; its syntax is: ContainingClass::staticMethodName.

• • •

As needed, the same method reference or lambda can be assigned to different functional interfaces.

avatar

NK Chauhan

NK Chauhan is a Principal Software Engineer with one of the biggest E Commerce company in the World.

Chauhan has around 12 Yrs of experience with a focus on JVM based technologies and Big Data.

His hobbies include playing Cricket, Video Games and hanging with friends.

Categories
Spring Framework
Microservices
BigData
Core Java
Java Concurrency