代理会在运行时创建一个实现了一组给定接口的新类。
创建的代理类名字以$Proxy开头,并且是public和final的。
创建代理类时需要提供一个实现了InvocationHandler接口的调用处理器,
无论何时调用代理对象的方法,调用处理器的invoke方法都会被调用,并向其传递Method和原始对象的调用参数
自定义接口
public interface MyInterface { void showMessage(String msg); } public class MyHandler implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("执行invoke"); if (args != null && args.length > 0) { for (int i = 0; i < args.length; i++) { System.out.println(" 参数: " + args[i]); } } return null; } } public class YProxy { public static void main(String[] mainArgs) { MyInterface proxyObject = (MyInterface) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] {MyInterface.class}, new MyHandler()); proxyObject.showMessage("Hello World!"); } }
Comparable接口
public class YProxy { public static void main(String[] mainArgs) { // 1,2,3,4,5,6,7,8,9,10 Object[] elements = new Object[10]; for (int i = 0; i < elements.length; i++) { Integer value = i + 1; InvocationHandler handler = new TraceHandler(value); Object proxy = Proxy.newProxyInstance(null, new Class[] { Comparable.class }, handler); elements[i] = proxy; } // 二分法检索 int result = Arrays.binarySearch(elements, 3); System.out.println("结果: " + elements[result]); } // 显示比较过程 static class TraceHandler implements InvocationHandler { private Object target; TraceHandler(Object value) { target = value; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (args != null) { System.out.println(target + "." + method.getName() + "(" + args[0] + ")"); } return method.invoke(target, args); } } } 5.compareTo(3) 2.compareTo(3) 3.compareTo(3) 结果: 3