Method Reference in Java (Instance, Static, and Constructor Reference)
- 4.1/5
- 5083
- Jul 20, 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.