Java 8中的功能接口(方法执行时间记录器)

Nit*_*inS 3 java java-8 functional-interface

我有两种方法:

class C1
{

  void m1() {//does sth}

  void m2(int x1, int x2) {//does sth}

 }
Run Code Online (Sandbox Code Playgroud)

//记录任何方法所用的时间

 logMethodExecTime(m1);
 logMethodExecTime(m2);
Run Code Online (Sandbox Code Playgroud)

不知道如何使用JDK8功能接口和方法引用来定义方法'logMethodExecTime'的正确语法?

以下不起作用:

class Utils
{
   public static void logMethodExecTime(Supplier<Void> s)
   {
     long start = System.nanoTime();
     s.get();
     long end = System.nanoTime();
     System.out.println(((end-start)/1000000000d) + " secs");
   }
 }
Run Code Online (Sandbox Code Playgroud)

和调用:

      C1 c = new C1();  
      Utils.logMethodExecTime(c::m1);

//Also how can we have one single definition of 'logMethodExecTime' 
//to accept any method with any number of args    
      Utils.logMethodExecTime(c::m2);
Run Code Online (Sandbox Code Playgroud)

Mar*_*nik 10

而不是Supplier<Void>你应该使用普通的Runnable,而不是坚持方法引用,你需要一个包含方法调用的显式lambda,捕获它需要的任何参数.例如:

logMethodExecTime(() -> m2(17, 37));
Run Code Online (Sandbox Code Playgroud)

请注意,lambda不一定只是一个方法调用.这使您可以更灵活地测量.