我可以将一个方法作为java中另一个方法的参数传递吗?
问题描述:
我正在尝试测量几种方法的执行时间。所以我想多做一个方法而不是重复相同的代码。
I am trying to measure the execution time for several methods. so I was thinking to make a method instead of duplicate same code many times.
这是我的代码:
private void MeasureExecutionTime(Method m)
{
startTime = System.nanoTime();
try
{
m();
}
finally
{
endTime = System.nanoTime();
}
elapsedTime = endTime - startTime;
System.out.println("This takes " + elapsedTime + " ns.");
}
假设我有 myMethod()
,如何使用 MeasureExecutionTime()
来衡量 myMethod
的执行时间?
Suppose I have myMethod()
, how can I use MeasureExecutionTime()
to measure myMethod
's execution time?
答
方法不是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(); } });