在 Java 中如何将可执行块作为参数传递?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18582807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 09:14:06  来源:igfitidea点击:

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

javarefactoringcode-design

提问by Keale

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.

或类似的东西。它实际上比这更复杂,我只是简化了问题。我正在尝试重构我的项目,并创建了一个通用实用程序类,其中包含我的类使用的静态方法。

采纳答案by Ted Hopp

You can use Runnableobjects:

您可以使用Runnable对象:

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:

编辑(抱歉,@Bohemian):在 Java 8 中,可以使用 lambdas 简化调用代码:

someMethod(flag, () -> { /* block 1 */ }, () -> { /* block 2 */ });

You'd still declare someMethodthe same way. The lambda syntax just simplifies how to create and pass the Runnables.

你仍然会someMethod以同样的方式声明。lambda 语法只是简化了如何创建和传递Runnables。

回答by Ted Hopp

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.

在 Java 8 中,您将能够传递 lambda 表达式,例如谓词和函数,这将使代码更简洁,但本质上做同样的事情。