Is there a way to pass an executable block as a parameter to a static method? Is it possible at all? For example I have this method
public static void someMethod(boolean flag, Block block1, BLock block2) { //some other code if(flag) block1.execute(); else block2.execute(); //some other code }
or something like that. It's actually more complicated than this, I just simplified the question. I am trying to refactor my project and I created a generic utility class that contains static methods that my classes use.
Information can be passed to methods as parameter. Parameters act as variables inside the method. Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.
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.
A parameter is a variable used to define a particular value during a function definition. Whenever we define a function we introduce our compiler with some variables that are being used in the running of that function. These variables are often termed as Parameters.
You can use Runnable
objects:
public static void someMethod(boolean flag, Runnable block1, Runnable block2) { //some other code if(flag) block1.run(); else block2.run(); //some other code }
Then you can call it with:
Runnable r1 = new Runnable() { @Override public void run() { . . . } }; Runnable r2 = . . . someMethod(flag, r1, r2);
EDIT (sorry, @Bohemian): in Java 8, the calling code can be simplified using lambdas:
someMethod(flag, () -> { /* block 1 */ }, () -> { /* block 2 */ });
You'd still declare someMethod
the same way. The lambda syntax just simplifies how to create and pass the Runnable
s.
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