How does Java 8 pass non functional methods as parameters
•
Java
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
二维码
