I have an array of strings containing names of classes. Is it possible to invoke the static methods of the actual class using the ‘name of the class’ in the string array.
public class SortCompare {
// There are classes called 'Insertion', 'Selection' and 'Shell' which have a
// method called 'sort'
private static String[] algorithm = { "Insertion", "Selection", "Shell"};
public static double timeTheRun(String alg, Comparable[] a) {
for (int i = 0; i < algorithm.length; i++)
if (alg.equalsIgnoreCase(algorithm[i])) {
Stopwatch timer = new Stopwatch();
// I want to invoke one of Insertion.sort(), Selection.sort()
// or Shell.sort() depending on the value of 'alg' here
break;
}
return timer.elapsedTime();
}
I could forget about the array of strings and simple use a if-else block to invoke them.
if (alg.equals("Insertion"))
Insertion.sort(a);
else if (alg.equals("Selection"))
Selection.sort(a);
else if (alg.equals("Shell"))
Shell.sort(a);
But I will keep implementing other sorts and variations of them in future and every time I will have to make changes in multiple places(The above if-else loop, the help message of my program). If the former approach is possible then I’ll just have to insert an extra string to the array every time.
The better way to implement this would be to create a common interface for your sorting algorithms:
Then have all your algorithms implement that interface:
and make the parameter to your method take an implementation of the interface:
You would then call that method like this:
This has the disadvantage that you cannot make the sorting-routine a static method, though.
Alternative If you insist on static methods, make your routine take a class-object as parameter:
Note that you will either have to add a try-catch-block or a throws declaration for the various exceptions that the reflection methods can throw. Then you can call it like this: