public ArithmeticCalculator getLoggingProxy() { ArithmeticCalculator proxy = null; // 代理对象由哪一个加载器进行加载 ClassLoader loader = target.getClass().getClassLoader(); // 代理对象的类型,即其中有哪些方法 Class[] interfaces = new Class[] {ArithmeticCalculator.class}; // 调用代理对象其中的方法时,实际执行的代码 InvocationHandler h = new InvocationHandler() { /** proxy:正在返回的那个代理对象,一般情况下不适用 method:正被调用的方法 args:调用方法的参数 */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); // 日志 System.out.println( "The method " + methodName + " begins with " + Arrays.asList((args))); // 执行方法 Object result = null; try { // 前置通知 result = method.invoke(target, args); // 返回通知 } catch (IllegalAccessException e) { e.printStackTrace(); // 异常通知,可以访问方法出现的异常 } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } // 后置通知,方法可能异常,访问不到返回值 System.out.println("The method " + methodName + " ends with " + result); return result; } }; proxy = (ArithmeticCalculator) Proxy.newProxyInstance(loader, interfaces, h); return proxy; }