How does Java 8 pass non functional methods as parameters

See English answers > java pass method as parameter 15

Class SimpleClass {
    methodA(var1,var2) {
      //body
    }

    methodB(var1,var2) {
      //body
    }
    ....

}

Using java 8 lambda, can I send one of the above methods as a parameter to another function of another class? As follows:

Class Service {
   doService(Method arg) {
     //Invoke passed simple class method here
     arg()
   }

}

Solution

If doservice has the appropriate signature, you can write:

service.doService(mySimpleClass::methodA);

Complete example:

class SimpleClass {
  public void methodA(String a,String b) {
    System.out.println(a + b);
  }
  //other methods
}

class Service {
  public void doService(BiConsumer<String,String> consumer) {
    consumer.accept("Hel","lo");
  }
}

public static void main(String[] args) {
  SimpleClass sc = new SimpleClass();
  new Service().doService(sc::methodA); //prints Hello
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>