Java Lambda Expression Method References to static Methods

Introduction

A method reference can refer to a method without executing it.

When evaluated, a method reference also creates an instance of the functional interface.

Method References to static Methods

To create a static method reference, use this general syntax:

ClassName::methodName 

This method reference can be used anywhere in which it is compatible with its target type.

// Demonstrate a method reference for a static method. 

// A functional interface for string operations. 
interface MyInterface {
  String func(String n);/*www . j  a va  2  s  . c  om*/
}

// This class defines a static method called strReverse().
class MyClass {
  // A static method that reverses a string.
  static String strReverse(String str) {
    String result = "";
    int i;

    for (i = str.length() - 1; i >= 0; i--)
      result += str.charAt(i);

    return result;
  }
}

public class Main {

  static String stringOp(MyInterface sf, String s) {
    return sf.func(s);
  }

  public static void main(String args[]) {
    String inStr = "demo from demo2s.com";
    String outStr;

    // Here, a method reference to strReverse is passed to stringOp().
    outStr = stringOp(MyClass::strReverse, inStr);

    System.out.println("Original string: " + inStr);
    System.out.println("String reversed: " + outStr);
  }
}



PreviousNext

Related