I have a 5 functions defined in a class. In another class I have a multiple looped structure that tries computing the time taken my each of the aforementioned functions on a input file containing many strings.
I want the output such that for each entry of the input file, the average time taken by each function over 10 calls is computed and printed out. So, the output should be like –
inputString | function1AvgTime | f2AvgTime and so on.
I cannot figure out an elegant way to call all these 5 functions 10 times each for a single input string. Right now what i seem to be doing is this –
for (inputString):
for (iteration 1 to 10):
call function 1
for (iteration 1 to 10):
call function2
and so on....
Is there a way to store the function names in an array or some datastructure, and call them within a single iteration loop? My work is getting done anyway. I’m just curious if there is a better design.
Use the
Runnableinterface,Then use anonymous local classes to wrap the individual functions, i.e.
This is somewhat in line with the Java API.
Runnableis a key interface used by Java all over the place. At the same time, it usually is only executed once, I believe. So it’s up to you to ensure it can be run multiple times!But so far, you have gained not much over the explicit
forloop, except the ability to store theRunnables in a collection:If you want to avoid writing the
Runnables yourself, your can use Java reflection to get the methods byStringname, or even via full introspection. Essentially, you’d then write oneRunnablethat executes onejava.lang.reflect.Method. The Runnable approach is a bit more flexible, because you can also do things such as:To run the same functions with different parameters.