Fully working example
import java.util.function.BiConsumer;
class SimpleClass {
void methodA(String a, String b) {
System.out.printf("%s %s", a, b);
}
}
class Service {
void doService(BiConsumer<String,String> method) {
method.accept("Hola", "mundo");
}
}
class Main {
public static void main( String ... args ) {
SimpleClass sc = new SimpleClass();
Service s = new Service();
s.doService(sc::methodA);
}
}
Because there are no function types in Java 8 you have to specify your service signature to accept one of the functional interfaces.
In general terms if the method accepts arguments but doesn't returns a result: it's a Consumer
. If it returns a Boolean then it's a Predicate
and if it returns some other value it's a Function
. There are others like Supplier
and others.
In an ideal world we would've written:
class Service {
void doService( void(String,String) method /*<-- fictional method type*/ ) {
method("Hello", "world");
}
}
But we have to use those functional interfaces at the moment.
This is a very good read about method references in Java 8