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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)