public class LawyerProxy implements InvocationHandler { private Object obj; public LawyerProxy(Object obj) { this.obj = obj; }
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if(method.getName().equals(“speak”)) { System.out.println(“引用法律条文”); method.invoke(obj,args); System.out.println(“道德层面批评”); } return null; } }
测试类 public class test { public static void main(String[] args) { //静态代理 Speaker speaker = new ZhangSanLawyer(); speaker.speak(); //动态代理 LawyerProxy lawyerProxy = new LawyerProxy(new ZhangSan());//抽象代理对象行为 //下面用到Speaker接口,也就是说jdk实现动态代理需要被代理类有实现接口 Speaker speaker1 = (Speaker) Proxy.newProxyInstance(test.class.getClassLoader(),new Class[]{Speaker.class},lawyerProxy); speaker1.speak();
} }
CGLIB动态代理不需要本体实现接口,是jdk动态代理的补充
下面李四本体没有实现接口
public class Lisi { public void speak() { System.out.println("李四说: 夫妻情感破裂"); } } public class LawyerInteceptor implements MethodInterceptor { private Object obj; public LawyerInteceptor(Object obj) { this.obj = obj; } @Override //回调方法 public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { if(method.getName().equals("speak")) { System.out.println("引用法律条文"); method.invoke(obj,args); System.out.println("道德层面批评"); } return null; } public class test { public static void main(String[] args) { //静态代理 Speaker speaker = new ZhangSanLawyer(); speaker.speak(); //动态代理 LawyerProxy lawyerProxy = new LawyerProxy(new ZhangSan());//抽象代理对象行为 Speaker speaker1 = (Speaker) Proxy.newProxyInstance(test.class.getClassLoader(),new Class[]{Speaker.class},lawyerProxy); speaker1.speak(); LawyerInteceptor lawyerInteceptor = new LawyerInteceptor(new Lisi());//抽象代理对象行为 Lisi lisi = (Lisi)Enhancer.create(Lisi.class,lawyerInteceptor); lisi.speak(); } }