java 把方法当参数传递,我可以将一个方法作为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.

Here is my code:

private void MeasureExecutionTime(Method m)

{

startTime = System.nanoTime();

try

{

m();

}

finally

{

endTime = System.nanoTime();

}

elapsedTime = endTime - startTime;

System.out.println("This takes " + elapsedTime + " ns.");

}

Suppose I have myMethod(), how can I use MeasureExecutionTime() to measure myMethod's execution time?

解决方案

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(); } });

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值