sneha
sneha

Reputation: 95

Java dynamically change function name in loop

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.

Upvotes: 1

Views: 1813

Answers (1)

Has QUIT--Anony-Mousse
Has QUIT--Anony-Mousse

Reputation: 77454

Use the Runnable interface,

void runMultipleTimes(Runnable run, int times) {
    for (int i = 0; i < times; i++) {
        run.run();
    }
}

Then use anonymous local classes to wrap the individual functions, i.e.

runMultipleTimes(new Runnable() {
    @Override
    void run() {
        function1();
    }
}, 10 /* how often to run */);

This is somewhat in line with the Java API. Runnable is 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 for loop, except the ability to store the Runnables in a collection:

for (Runnable run : runCollection) {
    runMultipleTimes(run, 100);
}

If you want to avoid writing the Runnables yourself, your can use Java reflection to get the methods by String name, or even via full introspection. Essentially, you'd then write one Runnable that executes one java.lang.reflect.Method. The Runnable approach is a bit more flexible, because you can also do things such as:

runCollection.add(new Runnable() {
    @Override
    void run() {
        function(123456);
    }
});

runCollection.add(new Runnable() {
    @Override
    void run() {
        function(654321);
    }
});

To run the same functions with different parameters.

Upvotes: 4

Related Questions