"Algorithms" by Robert Sedgewick, p256, SortCompare.time():
public static double time(String alg, Double[] a) throws SecurityException, NoSuchMethodException, ClassNotFoundException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { Stopwatch timer = new Stopwatch(); String originClassName = new Object(){}.getClass().getEnclosingClass().getName(); String packageName = originClassName.substring(0, originClassName.lastIndexOf(".")); String className = packageName.concat("." + alg); Class<?> clazz = Class.forName(className); Method sortMethod = clazz.getDeclaredMethod("sort", Comparable[].class); Object[] param = { a }; sortMethod.invoke(null, param); return timer.elapsedTime(); }
这里面注意的有两点,一是在static方法里获取所在类名的方法,二是如何用反射调用参数为数组的方法(见笔记 用反射机制在运行时创建对象并执行方法 )。