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.
You can use
Runnable
objects:Then you can call it with:
EDIT (sorry, @Bohemian): in Java 8, the calling code can be simplified using lambdas:
You'd still declare
someMethod
the same way. The lambda syntax just simplifies how to create and pass theRunnable
s.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:
and an implementing class:
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.