How to create a general placeholder function in Java and use the function as a parameter later?
I don't know how to express my question, but it's simple I want to create a generic placeholder function that takes a parameter from an existing function Let me give you an example For simplicity, suppose I want to know how long a function takes to execute in milliseconds
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"); } }
If you need to express my question better, please feel free to edit my question
Solution
Using java 8 Lambdas and functional interfaces, you can accept runnable, which performs some general, unspecified operations
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"); }
Then you call it:
tiMetakenFunc(() -> foo(arr)); tiMetakenFunc(() -> bar(arr));
This is the abbreviation of the former lambda equivalent:
tiMetakenFunc(new Runnable() { @Override public void run() { foo(arr); } }); tiMetakenFunc(new Runnable() { @Override public void run() { bar(arr); } });
I deleted the int [] a parameter because it is not necessarily needed here As you can see, arr can be embedded in runnable If you want to keep it as a parameter, you can switch from runnable to consumer < 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"); }
tiMetakenFunc(arr -> foo(arr),A); tiMetakenFunc(arr -> bar(arr),A);
Or, using method references with::, you can write:
tiMetakenFunc(Example::foo,A); tiMetakenFunc(Example::bar,A);
Both are equivalent to this pre lambda Code:
tiMetakenFunc(new Consumer<int[]>() { @Override public void accept(int[] arr) { foo(arr); } }); tiMetakenFunc(new Consumer<int[]>() { @Override public void accept(int[] arr) { bar(arr); } });