Home >Java >javaTutorial >How Can I Pass Functions as Arguments in Java?
Passing Functions as Arguments in Java
In Java, the ability to pass functions as arguments enhances the versatility of code. To achieve this, there are various approaches depending on the Java version you are using.
Java 8 and Above
With the advent of lambda expressions in Java 8, passing functions as arguments becomes straightforward. Lambda expressions allow you to define anonymous functions that implement a single-abstract-method (SAM) interface. For instance, you can define the following interface:
public interface MyInterface { String doSomething(int param1, String param2); }
Within a method that accepts an argument of type MyInterface, you can now use lambda expressions to pass a function as follows:
class MyClass { public MyInterface myInterface = (p1, p2) -> { return p2 + p1; }; }
Before Java 8
Prior to Java 8, the common approach to pass functions as arguments was to encapsulate them within an interface like Callable. Consider the following method:
public T myMethod(Callable<T> func) { return func.call(); }
This method accepts an argument of type Callable, which represents a function that returns a value of type T. You can define a Callable implementation to encapsulate your function and pass it as an argument to myMethod.
Example Usage:
If you have a method called methodToPass that you want to pass as an argument, you can create a Callable implementation as follows:
public int methodToPass() { // do something } public void dansMethod(int i, Callable<Integer> myFunc) { // do something }
And then call the dansMethod method with the Callable implementation:
dansMethod(100, new Callable<Integer>() { public Integer call() { return methodToPass(); } });
Conclusion:
These approaches provide different ways to pass functions as arguments in Java, depending on your Java version and specific requirements. By understanding these techniques, you can enhance the flexibility and reusability of your Java code.
The above is the detailed content of How Can I Pass Functions as Arguments in Java?. For more information, please follow other related articles on the PHP Chinese website!