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

前端 未结 6 510
隐瞒了意图╮
隐瞒了意图╮ 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:38

    You are in the correct path, you need to pass the Method object, the target object on which to execute the method and the arguments it takes and then invoke it into your try catch, something like:

    private void MeasureExecutionTime(Method m, Object target, Object args) 
                                throws IllegalArgumentException, 
                                       IllegalAccessException, 
                                       InvocationTargetException
    {
        long startTime = System.nanoTime();
        long endTime;
        try
        {
            m.invoke(target, args);
        }
        finally
        {
            endTime = System.nanoTime();
        }
        long elapsedTime = endTime - startTime;
        System.out.println("This takes " + elapsedTime + " ns.");
    }
    

提交回复
热议问题