Java Method References
Java provides a new feature called method reference in Java 8.
Method reference is used to refer method offunctional interface.
It is compact and easyform of lambda expression.
Each time when you are using lambda expression to just referring a method,
you canreplaceyourlambda expressionwithmethod reference.
Types of Method References
- Reference to a
static method. - Reference to an
instance method. - Reference to a
constructor.
Reference to a 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.
Syntax
ContainingClass::staticMethodName
Example
1 | public class StaticMethodReference { |
Output
This is a static method!
Reference to an Instance Method
like static methods,you can refer instance methods also.
Syntax
containingObject::instanceMethodName
Example
1 | public class InstanceMethodReference{ |
Output
This is instance method!
Reference to a Constructor
You can refer a construct by using the
newkeyword.
Syntax
ClassName::new
Example
1 | public class ConstructorReference { |
Output
Hello!