接着JDK 的动态代理的内容一起写的
①目标类
public class GirlWaiter{ public void serve() { System.out.println("上菜"); }}
public class Advice { public void smile() { System.out.println("微笑服务"); } public void discount() { System.out.println("打折服务"); }}
②动态代理代码
public class test { public static void main(final String[] args) { final GirlWaiter girlWaiter = new GirlWaiter();//目标对象 final Advice a = new Advice();//增强对象 //返回值 就是动态生成的代理对象 基于cglib //1.创建增强器 Enhancer enhancer = new Enhancer(); //2.设置父类 enhancer.setSuperclass(GirlWaiter.class); //3.设置父类 enhancer.setCallback(new MethodInterceptor() { public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { a.smile(); Object invoke = method.invoke(girlWaiter, args); a.discount(); return invoke; } }); //4.创建代理对象 GirlWaiter proxy = (GirlWaiter) enhancer.create(); proxy.serve(); }}
原文地址:https://www.cnblogs.com/duansuzhexie/p/10964481.html
时间: 2024-10-09 01:01:18