Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass a Method as parameter of another method in 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?

like image 868
Eng.Fouad Avatar asked May 19 '11 15:05

Eng.Fouad


1 Answers

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(); } });
like image 122
Oliver Charlesworth Avatar answered Oct 09 '22 12:10

Oliver Charlesworth