What is method reference in java

March 19, 2020 | No comments

What is method reference in java

In Java (Java 8 and after), we can refer a method from class or object using class::methodName syntax. It is a special form of lambda expression to access methods. It is compact and more readable.
Different flavours of method reference
  • Static method reference.
  • Instance method reference of a particular object.
  • Instance method reference of an arbitrary object of a particular type.
  • Constructor reference.

Example of method reference

Static method reference example
Let's start with a simple example to convert List of Integers to List of Strings. See the use of String::valueOf. Essentially we are invoking the static method valueOf method on String Class.
List nums = Arrays.asList(1, 2, 3, 4, 5);
//with static method reference
List str = nums.stream().map(String::valueOf).collect(Collectors.toList());
//with lambda expression
List strs = nums.stream().map(num -> String.valueOf(num)).collect(Collectors.toList());
Instance method reference example
Following code snippet show example of invoking an instance method. printWithPadding from class ExampleClass
MyFunction fn = ExampleClass::printWithPadding;
constructor reference example
Following code snippet shows how we can invoke the constructor using method reference.
MyFunction fn = ExampleClass::new;

    No comments :

    Post a Comment

    Please leave your message queries or suggetions.