Currently getting into Java 8 lambda expressions and method references.
I want to pass a method with no args and no return value as argument to another method. This is how I am doing it:
public void one() { System.out.println("one()"); } public void pass() { run(this::one); } public void run(final Function function) { function.call(); } @FunctionalInterface interface Function { void call(); }
I know there is a set of predefined functional interfaces in java.util.function
such as Function<T,R>
but I didn't find one with no arguments and not producing a result.
There's no concept of a passing method as a parameter in Java from scratch. However, we can achieve this by using the lambda function and method reference in Java 8.
We can't directly pass the whole method as an argument to another method. Instead, we can call the method from the argument of another method. // pass method2 as argument to method1 public void method1(method2()); Here, the returned value from method2() is assigned as an argument to method1() .
In Java, we can pass a reference to an object (also called a "handle")as a parameter.
It really does not matter; Runnable
will do too.
Consumer<Void>, Supplier<Void>, Function<Void, Void>
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