JDK动态代理
应用
为每个排序方法计算其运行时间
1 2 3 4 5 6 7 8 9 10 11
| public interface SortMethods { void bubbleSort(int[] arr); void selectSort(int[] arr); void insertSort(int[] arr); void quickSort(int[] arr); }
|
1 2 3 4
| public class SortMethodsImpl implements SortMethods { }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
public class RunTimeProxy implements InvocationHandler { private Object target;
public Object bind(Object target) { this.target = target; return Proxy.newProxyInstance( this.target.getClass().getClassLoader(), this.target.getClass().getInterfaces(), this); }
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.print("执行" + Thread.currentThread().getStackTrace()[2].getMethodName() + "方法"); long start = System.currentTimeMillis(); Object invoke = method.invoke(target, args); long runTime = System.currentTimeMillis() - start; System.out.println("总耗时" + runTime + "毫秒"); return invoke; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| public class Test { public static int[] generateRandomArray(int length, int min, int max) { if (max - min < 1 || length < 1) { throw new IllegalArgumentException("参数异常"); } int[] array = new int[length]; double random; for (int i = 0; i < length; i++) { random = Math.random() * (max + 1 - min) + min; array[i] = (int) random; } return array; }
public static void main(String[] args) { RunTimeProxy runTimeProxy = new RunTimeProxy(); SortMethods sortMethodsAndGetRunTime = (SortMethods) runTimeProxy.bind(new SortMethodsImpl()); sortMethodsAndGetRunTime.bubbleSort(generateRandomArray(10000, -100, 100)); sortMethodsAndGetRunTime.insertSort(generateRandomArray(10000, -100, 100)); sortMethodsAndGetRunTime.selectSort(generateRandomArray(10000, -100, 100)); sortMethodsAndGetRunTime.quickSort(generateRandomArray(10000, -100, 100));
} }
|
可以发现, 快排效率确实很高, 当数组越长时, 差距越明显.