//一个通告或建议的接口 public interface Advice { void afterMethod(Method method); void beforeMethod(Method method); } public class MyAdvice implements Advice{ private long start; @Override public void afterMethod(Method method) { System.out.println("运行时间计算结束!!"); System.out.println("共耗时:"+(System.currentTimeMillis()-start)); System.out.println("------------------------"); } @Override public void beforeMethod(Method method) { System.out.println("开始计算运行时间:"); start=System.currentTimeMillis(); System.out.println("所执行的方法:"+method.getName()); } } //编写可生成代理和插入通告的通用方法 public class Test1 { public static void main(String[] args) { final List target=new ArrayList(); Collection coll = (Collection) getProxy(target,new MyAdvice()); coll.add("111"); coll.add("222"); coll.add("333"); System.out.println(coll.size()); } //抽象出一个公共的方法 private static Object getProxy(final Object target,final Advice advice) { Object coll=(Object) Proxy.newProxyInstance( target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler(){ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { advice.beforeMethod(method); Object obj=method.invoke(target, args); advice.afterMethod(method); return obj; } }); return coll; } }