Thursday, April 18, 2019

Java 8 method reference

Java 8 provides a new feature call method reference. Method reference is used to refer method of functional interface.

There are 3 types of method reference as listed below.
  1. Reference to a static method
  2. Reference to an instance method
  3. Reference to a constructor
I'm going to use same sample to explain the way can use method reference.

1. Reference to a static method

Syntax:
ClassName::staticMethodName

Sample code:
public class MyPrinter { public static void print(String name) { System.out.println(name); } }


public class PrinterApp { public static void main(String[] args) { List<String> names = Arrays.asList("Tharanga", "Wijeweera"); names.forEach(MyPrinter::print); } }


2. Reference to an instance method

Syntax:
object::instanceMethodName

Sample code:
    public class MyPrinter {
     public void print(String name) {
         System.out.println(name);
     }
   }


public class PrinterApp {
public static void main(String[] args) { MyPrinter myPrinter = new MyPrinter(); List<String> names = Arrays.asList("Tharanga", "Wijeweera"); names.forEach(myPrinter::print); } }

3. Reference to a constructor

Syntax:
ClassName::new

Sample code:
    public class MyPrinter {

     private String name;

     public MyPrinter(String name) {
         this.name = name;
         print();
     }

     public void print() {
         System.out.println(this.name);
     }
    }


public class PrinterApp {
public static void main(String[] args) { List<String> names = Arrays.asList("Tharanga", "Wijeweera"); names.forEach(MyPrinter::new); } }

Hope this will help you to get an idea about the method reference in Java 8.

No comments:

Post a Comment