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!");
});
Other options
There are other functional interfaces you may be interested in, for example:
Supplier<T>
if you want to return a value ofT
without passing any parametersFunction<T,R>
if you want to pass a value ofT
and return a value ofR
Consumer<T>
if you want to pass valueT
as a parameter and returnvoid
Why there is no alternative for 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.