如何在Java中将可执行块作为参数传递? [英] 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.
推荐答案
你可以使用 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);
编辑(抱歉,@ Bohemian):在Java 8中,可以使用lambdas简化调用代码:
EDIT (sorry, @Bohemian): in Java 8, the calling code can be simplified using lambdas:
someMethod(flag, () -> { /* block 1 */ }, () -> { /* block 2 */ });
您仍然声明 someMethod
相同办法。 lambda语法只是简化了如何创建和传递 Runnable
s。
You'd still declare someMethod
the same way. The lambda syntax just simplifies how to create and pass the Runnable
s.
这篇关于如何在Java中将可执行块作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!