Java provides a new feature called method reference in Java 8. Method reference is used to refer method of functional interface. It is compact and easy form of lambda expression. Each time when you are using lambda expression to just referring a method, you can replace your lambda expression with method reference. Double colon (::) operator will be used in method references.
There are 3 types of method references
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:
ContainingClass::staticMethodName
In the following example, we have defined a functional interface and referring a static method to it's functional method say().
package com.java.session.seventeen;
interface CustomerMessage {
void writeMessage(String message);
}
public class FunctionalInterfaceExample {
public static void writeSomething(String message){
System.out.println("Hello guys, "+message);
}
public static void main(String[] args) {
// Referring static method
CustomerMessage sayable = FunctionalInterfaceExample::writeSomething;
// Calling interface method
sayable.writeMessage("welcome to java8 feature discussion");
}
}
Like static methods, you can refer instance methods also. In the following example, we are describing the process of referring the instance method.
Syntax:
ContainingObject::instanceMethodName
In the following example, we are referring non-static methods. You can refer methods by class object and anonymous object.
interface CustomerMessage {
void writeMessage(String message);
}
public class FunctionalInterfaceExample {
public void writeSomething(String message){
System.out.println("Hello guys, "+message);
}
public static void main(String[] args) {
// Referring instance method
FunctionalInterfaceExample functionalInterfaceExample = new FunctionalInterfaceExample();
CustomerMessage sayable = functionalInterfaceExample::writeSomething;
// Calling interface method
sayable.writeMessage("welcome to java8 feature discussion");
}
}
You can refer a constructor by using the new keyword. Here, we are referring constructor with the help of functional interface.
Syntax:
className::New
package com.java.session.seventeen;
interface CustomerMessage {
void writeMessage(String message);
}
public class FunctionalInterfaceExample {
FunctionalInterfaceExample(String message) {
System.out.println("Hello guys, "+message);
}
public static void main(String[] args) {
// Referring instance method
CustomerMessage functionalInterfaceExample = FunctionalInterfaceExample::new;
// Calling interface method
functionalInterfaceExample.writeMessage("welcome to java8 feature discussion");
}
}