Java Lambda Expression Method References to Instance Methods

Introduction

To pass a reference to an instance method on a specific object, use this basic syntax:

objRef::methodName 

// Demonstrate a method reference to an instance method 

// A functional interface for string operations. 
interface MyFunc {
  String func(String n);/* ww w.  ja  va2  s  .com*/
}

class MyClass {
  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(MyFunc sf, String s) {
    return sf.func(s);
  }
  public static void main(String args[]) {
    String inStr = "demo from demo2s.com";
    String outStr;

    // Create a MyStringOps object.
    MyClass strOps = new MyClass();

    // Now, a method reference to the instance method strReverse
    // is passed to stringOp().
    outStr = stringOp(strOps::strReverse, inStr);

    System.out.println("Original string: " + inStr);
    System.out.println("String reversed: " + outStr);
  }
}
interface Results {
  void doOperation();
}

public class Main {
  public static void main(String[] args) {
    Results results = My::show;//  ww w. j a  v  a 2 s . c  om
    results.doOperation();
    results = My::disp;
    results.doOperation();
    results = new My()::display;
    results.doOperation();
  }

}

class My {
  public static void show() {
    System.out.println("show() method is called");
  }

  public static void disp() {
    System.out.println("disp() method is called");
  }

  public void display() {
    System.out.println("display() method is called");
  }
}



PreviousNext

Related