In Java, how can one pass a function as an argument of another function?
Use an Instance of an interface to Pass a Function as a Parameter in Java. In this method, you need to write the function you need to pass as a parameter in a class implementing an interface containing that method's skeleton only.
Pass a Method as a Parameter by Using the lambda Function in Java. This is a simple example of lambda, where we are using it to iterate the ArrayList elements. Notice that we're passing the lambda function to the forEach() method of the Iterable interface. The ArrayList class implements the Iterable interface.
Java always passes arguments by value, NOT by reference.
Using Java 8+ lambda expressions, if you have a class or interface with only a single abstract method (sometimes called a SAM type), for example:
public interface MyInterface { String doSomething(int param1, String param2); }
then anywhere where MyInterface is used, you can substitute a lambda expression:
class MyClass { public MyInterface myInterface = (p1, p2) -> { return p2 + p1; }; }
For example, you can create a new thread very quickly:
new Thread(() -> someMethod()).start();
And use the method reference syntax to make it even cleaner:
new Thread(this::someMethod).start();
Without lambda expressions, these last two examples would look like:
new Thread(new Runnable() { someMethod(); }).start();
A common pattern would be to 'wrap' it within an interface, like Callable
, for example, then you pass in a Callable:
public T myMethod(Callable<T> func) { return func.call(); }
This pattern is known as the Command Pattern.
Keep in mind you would be best off creating an interface for your particular usage. If you chose to go with callable, then you'd replace T above with whatever type of return value you expect, such as String.
In response to your comment below you could say:
public int methodToPass() { // do something } public void dansMethod(int i, Callable<Integer> myFunc) { // do something }
then call it, perhaps using an anonymous inner class:
dansMethod(100, new Callable<Integer>() { public Integer call() { return methodToPass(); } });
Keep in mind this is not a 'trick'. It's just java's basic conceptual equivalent to function pointers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With