我有一个包含类名称的字符串数组。是否可以使用字符串数组中的'类的名称'来调用实际类的静态方法。有没有办法使用具有类名称的字符串来调用类的静态方法?
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();
}
我可以忘记字符串数组,并简单地使用if-else块来调用它们。
if (alg.equals("Insertion"))
Insertion.sort(a);
else if (alg.equals("Selection"))
Selection.sort(a);
else if (alg.equals("Shell"))
Shell.sort(a);
但我会继续实施其他类型和未来的每一次他们的变化,我将不得不在多个地方(以上的if-else循环,我的程序的帮助信息)的变化。如果前一种方法是可行的,那么我只需要每次向数组插入一个额外的字符串。
使用[的Class.forName](http://download.oracle.com/javase/1,5.0/docs/api/java/lang/Class.html#forName(java.lang.String中)) –
[如何在函数参数中传递类名](http:// stackoverflow。com/questions/6490810/how-to-pass-class-name-in-function-arguments) – flolo