Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a function as a parameter in Java? [duplicate]

Tags:

java

In Java, how can one pass a function as an argument of another function?

like image 282
Jason Avatar asked Jan 13 '11 21:01

Jason


People also ask

Can we pass function as a parameter in Java?

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.

How do you pass a method call as a parameter in Java?

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.

Does Java pass by reference or copy?

Java always passes arguments by value, NOT by reference.


1 Answers

Java 8 and above

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(); 

Before Java 8

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.

like image 186
jk. Avatar answered Oct 01 '22 10:10

jk.