Can I pass a Method as parameter of another method in java?

前端 未结 6 511
隐瞒了意图╮
隐瞒了意图╮ 2021-01-04 21:04

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:

6条回答
  •  死守一世寂寞
    2021-01-04 21:33

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

提交回复
热议问题