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.

Answer from jk. on Stack Overflow
Top answer
1 of 8
594

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.

2 of 8
133

You could use Java reflection to do this. The method would be represented as an instance of java.lang.reflect.Method.

import java.lang.reflect.Method;

public class Demo {

    public static void main(String[] args) throws Exception{
        Class[] parameterTypes = new Class[1];
        parameterTypes[0] = String.class;
        Method method1 = Demo.class.getMethod("method1", parameterTypes);

        Demo demo = new Demo();
        demo.method2(demo, method1, "Hello World");
    }

    public void method1(String message) {
        System.out.println(message);
    }

    public void method2(Object object, Method method, String message) throws Exception {
        Object[] parameters = new Object[1];
        parameters[0] = message;
        method.invoke(object, parameters);
    }

}
🌐
Baeldung
baeldung.com › home › java › how to pass method as parameter in java
How to Pass Method as Parameter in Java | Baeldung
July 11, 2024 - For the third argument, instead of an anonymous inner class, we pass a lambda expression (a, b) -> a + b, which represents an instance of the Operation functional interface. ... Using lambda expressions simplifies the syntax and makes the code more readable compared to anonymous inner classes. Method references in Java provide a streamlined way to pass methods as parameters.
Discussions

[Java] How do I pass a method as a parameter to another method?
you use a lambda, aka an anonymous function: https://stackoverflow.com/questions/2755445/how-can-i-write-an-anonymous-function-in-java More on reddit.com
🌐 r/learnprogramming
5
1
September 15, 2017
java - Passing a generic function as parameter - Code Review Stack Exchange
Ran into this idea and I'm curious if it's possible. I'm trying to make a single function that can test ALL of my sorting algorithms dynamically. I want to be able to pass the sorting function as a More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
February 7, 2018
interface - Java Pass Method as Parameter - Stack Overflow
Strategy encapsulates an algorithm, but accepts parameters. Though when "visiting" all the leaves of a container, as OP does, Visitor pattern is what comes to mind - that's the traditional use of Visitor pattern. Anyway, you have a good implementation, and it could be considered either Strategy or Visitor. 2015-09-05T15:14:22.247Z+00:00 ... In Java 8, you can now pass a method more easily using Lambda Expressions and Method References. First, some background: a functional ... More on stackoverflow.com
🌐 stackoverflow.com
How to use a function as a parameter? - Processing Forum
Yes, in Java, you cannot pass a function or a reference to a function. Usually, you make a class (or an interface) to wrap the function. That's the case of the Comparator interface, to name only one commonly used here. A bit verbose / heavy, but it works. ... There's no way of passing functions as parameters... More on forum.processing.org
🌐 forum.processing.org
October 20, 2012
🌐
W3Docs
w3docs.com › java
How to pass a function as a parameter in Java?
@FunctionalInterface interface Function { void apply(); } public class Main { public static void main(String[] args) { // Create a function that prints "Hello, World!" Function sayHello = () -> System.out.println("Hello, World!"); // Pass the function as a parameter to the runFunction() method runFunction(sayHello); } public static void runFunction(Function func) { func.apply(); } }
🌐
Reddit
reddit.com › r/learnprogramming › [java] how do i pass a method as a parameter to another method?
[Java] How do I pass a method as a parameter to another method? : r/learnprogramming
September 15, 2017 - I'd check out this stack overflow answer on passing functions as parameters. ... You can't pass methods in Java (edit: Not true in Java 8, which has lambdas). You have to pass an object.
Top answer
1 of 1
14

Note: This answer is based on Java 8 and newer. This does not apply to Java 7, as Java 7 does not support Lambda

For starters, your test function is wrong in multiple places:

boolean test(function someSortFunction){//This is not how you pass functions
    int n; //this has to be initialized
    for (int i=0; i<=n ; i++) {//Depending on how n is used, you may have to use < instead of <=
        int[] A = generateArray()//Missing semi-colon
        if (isSorted(someSortFunction(A)) = false) {//Comparing is done with ==, not =
            return false;
        }
    }
    return true;
}

In order to pass a function, you can either use Consumer<Void>, Supplier<Void>, Predicate<Void> or Function<Void, Void> (don't use Void as the type if you have return values)

Supplier defines return type, Consumer defines input type, and function both. Meaning:

  • Use Predicate when you have a boolean return type with arguments
  • Use Supplier when you have a return type
  • Use Consumer when you have an argument
  • Use Function when you have both an argument and a return value

Since you have both arguments and return types, use Function. The first argument you give it is the argument it receives, and the second is the return type. For an instance, in your case, this would be:

boolean test(Function<int[], int[]> someFunction) 

Using Function requires calling apply to execute the method:

int[] res = someFunction.apply(input);

Before I move on, I'd like to take a second to mention naming conventions. In Java, class names always start with an upper case letter. Instances and functions start with a lower case letter. So your classes would be:

public class ManyFunctions {...}
public class MainClass {...}

Passing methods are not done using someClass.someFunction. In your case, since you are not using static methods, you need to create an instance:

ManyFunctions functions = new ManyFunctions();

now, you pass the functions:

test(functions::mergeSort);

if you make the methods static, you can just skip the instance and use the class name directly:

test(ManyFunctions::mergeSort);

So your class would be:

class MainClass{
    public static void main(String[] args){
        ManyFunctions manyFunctions = new ManyFunctions();
        test(manyFunctions::mergeSort);//Notice the missing "()" and arguments
        test(manyFunctions::otherSort);

    }

    boolean test(Function<int[], int[]> someSortFunction){
        int n = 10;//THIS HAS TO BE INITIALIZED! Otherwise, it won't compile
        for (int i=0; i<=n ; i++) {
            int[] A = generateArray();
            if (isSorted(someSortFunction.apply(A)) == false) {//comparing is done with ==
                return false;
            }
         }
         return true;
    }
}//Don't know if it was a copy-paste problem or not, but you had a missing bracket
Top answer
1 of 16
291

As of Java 8, lambda expressions are a nice solution as other answers have pointed out. The answer below was written for Java 7 and earlier...


Take a look at the command pattern.

// NOTE: code not tested, but I believe this is valid java...
public class CommandExample 
{
    public interface Command 
    {
        public void execute(Object data);
    }

    public class PrintCommand implements Command 
    {
        public void execute(Object data) 
        {
            System.out.println(data.toString());
        }    
    }

    public static void callCommand(Command command, Object data) 
    {
        command.execute(data);
    }

    public static void main(String... args) 
    {
        callCommand(new PrintCommand(), "hello world");
    }
}

As Pete Kirkham points out, there's another way of doing this using a Visitor. The visitor approach is a little more involved - your nodes all need to be visitor-aware with an acceptVisitor() method - but if you need to traverse a more complex object graph, then it's worth examining.

2 of 16
117

In Java 8, you can now pass a method more easily using Lambda Expressions and Method References. First, some background: a functional interface is an interface that has one and only one abstract method, although it can contain any number of default methods (new in Java 8) and static methods. A lambda expression can quickly implement the abstract method, without all the unnecessary syntax needed if you don't use a lambda expression.

Without lambda expressions:

obj.aMethod(new AFunctionalInterface() {
    @Override
    public boolean anotherMethod(int i)
    {
        return i == 982
    }
});

With lambda expressions:

obj.aMethod(i -> i == 982);

Here is an excerpt from the Java tutorial on Lambda Expressions:

Syntax of Lambda Expressions

A lambda expression consists of the following:

  • A comma-separated list of formal parameters enclosed in parentheses. The CheckPerson.test method contains one parameter, p, which represents an instance of the Person class.

    Note: You can omit the data type of the parameters in a lambda expression. In addition, you can omit the parentheses if there is only one parameter. For example, the following lambda expression is also valid:

    p -> p.getGender() == Person.Sex.MALE 
        && p.getAge() >= 18
        && p.getAge() <= 25
    
  • The arrow token, ->

  • A body, which consists of a single expression or a statement block. This example uses the following expression:

    p.getGender() == Person.Sex.MALE 
        && p.getAge() >= 18
        && p.getAge() <= 25
    

    If you specify a single expression, then the Java runtime evaluates the expression and then returns its value. Alternatively, you can use a return statement:

    p -> {
        return p.getGender() == Person.Sex.MALE
            && p.getAge() >= 18
            && p.getAge() <= 25;
    }
    

    A return statement is not an expression; in a lambda expression, you must enclose statements in braces ({}). However, you do not have to enclose a void method invocation in braces. For example, the following is a valid lambda expression:

    email -> System.out.println(email)
    

Note that a lambda expression looks a lot like a method declaration; you can consider lambda expressions as anonymous methods—methods without a name.


Here is how you can "pass a method" using a lambda expression:

interface I {
    public void myMethod(Component component);
}

class A {
    public void changeColor(Component component) {
        // code here
    }

    public void changeSize(Component component) {
        // code here
    }
}
class B {
    public void setAllComponents(Component[] myComponentArray, I myMethodsInterface) {
        for(Component leaf : myComponentArray) {
            if(leaf instanceof Container) { // recursive call if Container
                Container node = (Container)leaf;
                setAllComponents(node.getComponents(), myMethodInterface);
            } // end if node
            myMethodsInterface.myMethod(leaf);
        } // end looping through components
    }
}
class C {
    A a = new A();
    B b = new B();

    public C() {
        b.setAllComponents(this.getComponents(), component -> a.changeColor(component));
        b.setAllComponents(this.getComponents(), component -> a.changeSize(component));
    }
}

Class C can be shortened even a bit further by the use of method references like so:

class C {
    A a = new A();
    B b = new B();

    public C() {
        b.setAllComponents(this.getComponents(), a::changeColor);
        b.setAllComponents(this.getComponents(), a::changeSize);
    }
}
🌐
Vultr Docs
docs.vultr.com › java › examples › pass-method-call-as-arguments-to-another-method
Java Program to pass method call as arguments to another method | Vultr Docs
December 23, 2024 - Recognize java.util.function package, ... an instance of a functional interface using an expression. Use lambda expressions to pass behavior as an argument....
Find elsewhere
🌐
W3Schools
w3schools.com › java › java_methods_param.asp
Java Method Parameters
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Server Java Syllabus Java Study Plan Java Interview Q&A Java Certificate ... Information can be passed to methods as a parameter.
🌐
Medium
medium.com › @jeffbicca › passing-a-method-as-argument-and-call-it-later-in-java-98c4d8528d6a
Passing a method as argument and call it later in Java | by Jefferson Bicca | Medium
September 11, 2018 - public class Router { public static final Map<String, Function<APayload, ClientResponse>> services = new HashMap<>(); static { Function<APayload, ClientResponse> post = RESTClientUtil::doPost; Function<APayload, ClientResponse> get = RESTClientUtil::doGet; Function<APayload, ClientResponse> put = RESTClientUtil::doPut; services.put("/oneEndpointPost", post); services.put("/oneEndpointGet", get); services.put("/oneEndpointPut", put); } ... } Finally we can then fire which request do based in the string (serviceUrl) passed as argument going directly to the Map’s key!
🌐
Codemia
codemia.io › knowledge-hub › path › how_to_pass_a_function_as_a_parameter_in_java
How to pass a function as a parameter in Java?
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises
🌐
Delft Stack
delftstack.com › home › howto › java › how to pass a function as a parameter in java
How to Pass a Function as a Parameter in Java | Delft Stack
February 2, 2024 - There is no difference in how we define functionToPass; however, we need to follow a specific syntax to define the outerFunction: outerFunction(Object object, Method method, param1, param2, ...). ... import java.lang.reflect.Method; public class ...
🌐
Medium
medium.com › @mibatman01 › pass-function-as-a-parameter-without-using-lambdas-in-java-5e002bbc3516
Pass “function” as a parameter without using “Lambdas” in JAVA | by shivam vishwakarma | Medium
August 3, 2023 - We can do the same without “Anonymous” function, all we need to explicitly create the class and implement the interface. public class Num { List<Integer>nums=new ArrayList<>(); Num() { //Adding integer into the list nums.add(1); nums.add(2); nums.add(3); nums.add(4); nums.add(5); nums.add(6); } //Passed the object of the Interface implementation //which contains the method test() public List<Integer>evenNum(CheckNum checkNum) { List<Integer>evenNumsList=new ArrayList<>(); for(var num:nums) if(checkNum.test(num)) evenNumsList.add(num); return evenNumsList; } }
🌐
TutorialsPoint
tutorialspoint.com › how-to-pass-a-function-as-a-parameter-in-java
How to pass a function as a parameter in Java
import java.util.List; import java.util.ArrayList; public class Java8Tester { public static void main(String args[]) { List names = new ArrayList(); names.add("Mahesh"); names.add("Suresh"); names.add("Ramesh"); names.add("Naresh"); names.add("Kalpesh"); names.forEach(System.out::println); } } Here we have passed System.out::println method as a static method reference.
🌐
W3Docs
w3docs.com › java
Java Pass Method as Parameter
For example: @FunctionalInterface public interface MyFunction { void apply(); } ... To pass a method as a parameter, you can create a lambda expression that implements the abstract method of the functional interface.
🌐
PREP INSTA
prepinsta.com › home › java tutorial › java program to pass method as an arguments to another method
Java Program to Pass Method as an Arguments | Prepinsta
May 31, 2023 - We can invoke methodTwo on the functional interface by passing methodOne an argument of type MethodTwoInterface. The methodTwo of Main that we passed in as a parameter will be executed when we call the functional interface.
🌐
Processing Forum
forum.processing.org › one › topic › how-to-use-a-function-as-a-parameter.html
How to use a function as a parameter? - Processing Forum
October 20, 2012 - Yes, in Java, you cannot pass a ... interface, to name only one commonly used here. A bit verbose / heavy, but it works. ... There's no way of passing functions as parameters......
🌐
Ted Vinke's Blog
tedvinke.wordpress.com › 2018 › 12 › 01 › functional-java-by-example-part-6-functions-as-parameters
Functional Java by Example | Part 6 – Functions as Parameters
June 9, 2020 - In this case we have to pass WebService in as a parameter, just as the list of documents. ... At every invocation of handle we pass in everything it needs: the documents it needs to handle and the webservice it needs to use.
🌐
javathinking
javathinking.com › blog › how-to-pass-a-function-as-a-parameter-in-java
How to Pass a Function as a Parameter in Java: Step-by-Step Guide with Examples — javathinking.com
This guide will walk you through everything you need to know to pass functions as parameters in Java, from the basics of functional interfaces to practical examples and common use cases.
🌐
Medium
dana-scheider.medium.com › parameter-passing-in-java-58858ad58a8e
Parameter Passing in Java. This is something I wrote about how… | by Dana Scheider (he/they) | Medium
April 28, 2017 - Java uses the pass by value method to associate actual parameters with the formal parameter names (Reid, n.d.), but I’ll explain both methods here as I enjoyed learning about them and hope others will as well.