Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you pass an executable block as a parameter in Java?

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.

like image 981
Keale Avatar asked Sep 03 '13 01:09

Keale


People also ask

How do you pass a method as a parameter in Java?

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.

Can you use methods as parameters in Java?

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.

What is function parameter in Java?

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.


1 Answers

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 Runnables.

like image 100
Ted Hopp Avatar answered Sep 27 '22 23:09

Ted Hopp