如何在Java中创建一个通用占位符函数,将函数作为参数以后使用?

dra*_*ore 3 java

我不知道如何表达我的问题,但这很简单.我想创建一个通用的占位符函数,它接受现有函数中的一个参数.让我给你举个例子.为了简单起见,假设我想知道函数在几毫秒内执行需要多长时间.

public class Example{
   public static void main(String[] args) {
      int arr[] = {30, 8, 21, 19, 50, ... , n};
      //needs to accept a function with a parameter as an argument.
      timeTakenFunc(foo(arr), arr);
      timeTakenFunc(bar(arr), arr);
   }

   public static void foo(int A[]){
     //do stuff
   }

   public static void bar(int A[]){
     //do stuff
   } 

   public static void timeTakenFunc(/*what goes here?*/, int A[]){
      long startTime = System.nanoTime();

      //placeholder for foo and bar function here
      placeholder(A);

      long endTime = System.nanoTime();
      long duration = ((endTime - startTime) / 1000000);
      System.out.println("function took: " + duration + "milliseconds");

   }
}
Run Code Online (Sandbox Code Playgroud)

如果需要更好地表达我的问题,请随意编辑我的问题.

Joh*_*ica 5

使用Java 8 lambdas功能接口,您可以接受Runnable执行某些通用的,未指定的操作的a.

public static void timeTakenFunc(Runnable func) {
  long startTime = System.nanoTime();

  //placeholder for foo and bar function here
  func.run();

  long endTime = System.nanoTime();
  long duration = ((endTime - startTime) / 1000000);
  System.out.println("function took: " + duration + "milliseconds");
}
Run Code Online (Sandbox Code Playgroud)

然后你会这样称呼它:

timeTakenFunc(() -> foo(arr));
timeTakenFunc(() -> bar(arr));
Run Code Online (Sandbox Code Playgroud)

这是前lambda等效的简写:

timeTakenFunc(new Runnable() {
    @Override public void run() {
        foo(arr);
    }
});
timeTakenFunc(new Runnable() {
    @Override public void run() {
        bar(arr);
    }
});
Run Code Online (Sandbox Code Playgroud)

我删除了int[] A参数,因为这里不一定需要它.如你所见,arr可嵌入其中Runnable.如果你想将它作为参数保存,那么你可以切换RunnableConsumer<int[]>.

public static void timeTakenFunc(Consumer<int[]> func, int[] A) {
  long startTime = System.nanoTime();

  //placeholder for foo and bar function here
  func.accept(A);

  long endTime = System.nanoTime();
  long duration = ((endTime - startTime) / 1000000);
  System.out.println("function took: " + duration + "milliseconds");
}
Run Code Online (Sandbox Code Playgroud)

timeTakenFunc(arr -> foo(arr), A);
timeTakenFunc(arr -> bar(arr), A);
Run Code Online (Sandbox Code Playgroud)

或者使用方法引用::,你可以这样写:

timeTakenFunc(Example::foo, A);
timeTakenFunc(Example::bar, A);
Run Code Online (Sandbox Code Playgroud)

这两个都等同于这个pre-lambda代码:

timeTakenFunc(new Consumer<int[]>() {
    @Override public void accept(int[] arr) {
        foo(arr);
    }
});
timeTakenFunc(new Consumer<int[]>() {
    @Override public void accept(int[] arr) {
        bar(arr);
    }
});
Run Code Online (Sandbox Code Playgroud)