且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我可以将一个方法作为java中另一个方法的参数传递吗?

更新时间:2023-02-14 16:11:28

方法不是Java中的第一类对象,因此它们不能作为参数传递。您可以在一个烦人的类中使用wrap方法调用,例如 Runnable 界面:

Methods aren't first-class objects in Java, so they can't be passed as parameters. You could use wrap your method call in an annoymous class that extends e.g. the Runnable interface:

private void MeasureExecutionTime(Runnable r) {
    r.run();
}

...


MeasureExecutionTime(new Runnable() { public void run() { m(); } });