java8 functional interface to handle the callback

Viewed 29737

I have a generic private method which does common tasks and is used by other methods. The generic method has if and else conditions to support other methods that are called. Example:

private void myGenericMethod(String name, int age){
  common task1;
  common task2;
  if(name!= null && name.length > 0){
     specific task 1;
     specific task 2;
  } else{
     specific task 3;
     specific task 4;
  }
  if(age > 18){
     specific task 1`;
     specific task 2`;
  }
}

I want to use Java 8 lambda and I have created a functional interface called Invoker with a invoke method.

public interface Invoker{
  public void invoke()
}

Now my generic method looks like this and the public method handles the invoke function callback appropriately:

private void myGenericMethod(Invoker invoker){
  common task1;
  common task2;
  invoker.invoke();
}  

Is there a functional interface in the JDK that I can use instead of creating this interface by myself?

3 Answers

There is also the possibility to use Consumer<Void>. It could look like this

public void init(Consumer<Void> callback) {
    callback.accept(null);
}

init((Void) -> done());

I suggest to use Consumer as callback interface. Comparing it with the JavaScript language, callbacks are bound with a scope. Therefore, if you make use of Consumer interface then you can pass the scope as parameter to the function. Ex:

public void startTracer(String tracerName, Event boundEvent) {
    executeOnTracer(tracer -> tracer.startTracer(tracerName, boundEvent));
}
...
private void executeOnTracer(Consumer<Tracer> callback) {
    TracerController tracer = null;
    if (isTracerActive()) {
        tracer = getTracer();
    }
    Optional.ofNullable(tracer).ifPresent(callback::accept);
}
Related