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

故事扮演 提交于 2019-11-30 12:47:05

问题


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.


回答1:


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.




回答2:


You can simply create an interface and pass objects from classes that implement that interface. This is known as the Command pattern.

For example, you could have:

public interface IBlock
{
   void execute();
}

and an implementing class:

public class Block implements IBlock
{
    public void execute()
    {
        // do something
    }
}

In Java 8 you will be able to pass lambda expressions such as predicates and functions which will make the code a little cleaner but essentially do the same thing.



来源:https://stackoverflow.com/questions/18582807/how-do-you-pass-an-executable-block-as-a-parameter-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!