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?
Package java.util.function
does not contain a functional interface with a method that does not require any parameter and returns void
. But you can use Runnable
interface instead.
private void myGenericMethod(Runnable runnable){
common task1;
common task2;
//consider checking if runnable != null to avoid NPE
runnable.run();
}
Then the invocation would look pretty simple:
myGenericMethod(() -> {
//do something fancy
System.out.println("Hello, world!");
});
There are other functional interfaces you may be interested in, for example:
Supplier<T>
if you want to return a value of T
without passing any parametersFunction<T,R>
if you want to pass a value of T
and return a value of R
Consumer<T>
if you want to pass value T
as a parameter and return void
Runnable
interface?Using Runnable
interface for a lambda that does not return nothing and does not expect any parameters may sound controversial for many programmers. Runnable
was invented for running a code in a separate thread and many programmers identify this class with multithreading. Even documentation says:
The
Runnable
interface should be implemented by any class whose instances are intended to be executed by a thread.
Someone already asked similar question 2 years ago and if you take a look at this comment and Brian Goetz's reaction to it you will understand that Java language designers came to a conclusion that there is no need to create another functional interface that mimics implementation of Runnable
interface.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With