HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaCritical

How to pass a function as a parameter in Java?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howjavafunctionparameterpass

Problem

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

Solution

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 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 myFunc) {
       // do something
}


then call it, perhaps using an anonymous inner class:

dansMethod(100, new Callable() {
   public Integer call() {
        return methodToPass();
   }
});


Keep in mind this is not a 'trick'. It's just java's basic conceptual equivalent to function pointers.

Code Snippets

public interface MyInterface {
    String doSomething(int param1, String param2);
}
class MyClass {
    public MyInterface myInterface = (p1, p2) -> { return p2 + p1; };
}
new Thread(() -> someMethod()).start();
new Thread(this::someMethod).start();
new Thread(new Runnable() { someMethod(); }).start();

Context

Stack Overflow Q#4685563, score: 594

Revisions (0)

No revisions yet.