publicclassProxyTest { publicstaticvoidmain(String[] args) { Object[] elements = new Object[1000];
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);//(ClassLoader,Class对象数组,InvocationHandler) elements[i] = proxy; }
// construct a random integer Integer key = new Random().nextInt(elements.length) + 1;
// search for the key int result = Arrays.binarySearch(elements, key);//会获取到elements中的Comparable接口,调用compareTo(),而在compareTo()中调用了代理对象的InvocationHandler的invoke()
// print match if found if (result >= 0) System.out.println(elements[result]); } }
/** * An invocation handler that prints out the method name and parameters, then * invokes the original method */ classTraceHandlerimplementsInvocationHandler { private Object target;
/** * Constructs a TraceHandler * @param t the implicit parameter of the method call */ publicTraceHandler(Object t) { target = t; }
public Object invoke(Object proxy, Method m, Object[] args)throws Throwable { // print implicit argument System.out.print(target); // print method name System.out.print("." + m.getName() + "("); // print explicit arguments if (args != null) { for (int i = 0; i < args.length; i++) { System.out.print(args[i]); if (i < args.length - 1) System.out.print(", "); } } System.out.println(")");
// invoke actual method return m.invoke(target, args); } }