Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass a method into another method in Java

Tags:

java

methods

For example I have the following method call:

Requests.sendGet("/type", Model.setTypes);

Model.setTypes is a setter for a List of Types, I want the sendGet method to be able to call whatever method gets passed into it, and no the sendGet method can't just call Model.setTypes itself, because it depends on what type of Get request is being performed.

Thanks to anyone who replies.

like image 570
adhanlon Avatar asked Feb 10 '26 22:02

adhanlon


2 Answers

Use the command pattern.

public interface Command {
    public void execute();
}

public class Requests {
    public static void sendGet(String url, Command command) {
        // Do your stuff here and then execute the command.
        command.execute();
    }
}

final Model model = getItSomehow(); // Must be declared final.
Requests.sendGet("/type", new Command() {
    public void execute() {
        model.setType();
    }
});

You can if necessary add an argument to execute() method, like RequestEvent which can be created by Requests#sendGet() and accessed in Command#execute().

like image 165
BalusC Avatar answered Feb 13 '26 11:02

BalusC


It is possible, although clumsy: You can use java.lang.reflect.Method to point to a method and call its invoke member to call it.

However, in almost all cases, this is not what you want to do. Instead, use an interface for that (i.e. your function accepts an object of a certain type that implements an interface), or you can take a Runnable and call the run() function of it, or a Callable and use call().

(Thanks to Crom for pointing out Callable)

like image 38
EboMike Avatar answered Feb 13 '26 10:02

EboMike



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!