public class DynamicProxy { // 动态代理 public static void main(String[] argsx) { Cat cat = new Cat(); /** * 三个参数(被代理类的ClassLoader, 实现的接口的数组, InvocationHandler接口的实现) */ Animal catProxy = (Animal)Proxy.newProxyInstance(Cat.class.getClassLoader(), new Class[]{Animal.class}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println(method.getName()+"-方法-------start-------"); Object invoke = method.invoke(cat, args); System.out.println(method.getName()+"-方法-------end-------"); return invoke; } }); catProxy.voice(); } // 被代理的类 static class Cat implements Animal{ @Override public void voice() { System.out.println("喵喵喵..."); } } // 被代理的类的接口 interface Animal{ void voice(); } }
原文:https://www.cnblogs.com/zhouxuezheng/p/14687091.html