Home >Java >javaTutorial >How Can Functions Be Passed as Parameters in Java?
Passing Functions as Parameters in Java
In Java, one can leverage Java 8's lambda expressions to pass a function as an argument. When working with interfaces containing a single abstract method (SAM types), lambda expressions can be substituted, allowing for concise code. For instance:
interface MyInterface { String doSomething(int param1, String param2); } MyInterface myInterface = (p1, p2) -> { return p2 + p1; };
Alternatively, method references can provide even cleaner syntax:
new Thread(this::someMethod).start();
Pre-Java 8 Approach
Prior to Java 8, the Command Pattern was commonly used to pass functions as arguments. This involved wrapping the function in an interface like Callable:
public T myMethod(Callable<T> func) { return func.call(); }
For example:
public int methodToPass() { return 3; } public void dansMethod(int i, Callable<Integer> myFunc) { }
To call the function, an anonymous inner class would be used:
dansMethod(100, new Callable<Integer>() { public Integer call() { return methodToPass(); } });
Remember that this approach is essentially equivalent to function pointers in other languages.
The above is the detailed content of How Can Functions Be Passed as Parameters in Java?. For more information, please follow other related articles on the PHP Chinese website!