我可以将方法传递给Java中的另一个方法

adh*_*lon 2 java methods

例如,我有以下方法调用:

Requests.sendGet("/type", Model.setTypes);
Run Code Online (Sandbox Code Playgroud)

Model.setTypes是List of Types的setter,我希望sendGet方法能够调用传递给它的任何方法,并且sendGet方法不能只调用Model.setTypes本身,因为它取决于什么类型正在执行Get请求.

感谢任何回复的人.

Bal*_*usC 7

使用命令模式.

public interface Command {
    public void execute();
}
Run Code Online (Sandbox Code Playgroud)
public class Requests {
    public static void sendGet(String url, Command command) {
        // Do your stuff here and then execute the command.
        command.execute();
    }
}
Run Code Online (Sandbox Code Playgroud)
final Model model = getItSomehow(); // Must be declared final.
Requests.sendGet("/type", new Command() {
    public void execute() {
        model.setType();
    }
});
Run Code Online (Sandbox Code Playgroud)

您可以根据需要为execute()方法添加一个参数,例如RequestEvent可以创建Requests#sendGet()和访问的方法Command#execute().


Ebo*_*ike 5

这是可能的,尽管很笨拙:您可以使用java.lang.reflect.Method指向一个方法并调用其invoke成员来调用它。

然而,在几乎所有情况下,这都不是您想要做的。相反,为此使用接口(即您的函数接受实现接口的某种类型的对象),或者您可以采用 aRunnable并调用它的 run() 函数,或者 aCallable并使用call()

(感谢克罗姆指出Callable