1. 导入spring-core.jar
2. 接口:
//邓紫棋服务菜单 : 唱歌,跳舞 interface IDengziqi { void sing(); void dance(); }
3.目标对象, 不用实现接口
//目标对象 , 邓紫棋实实在在的在唱歌和跳舞 public class Dengziqi { public void sing() { System.out.println("邓紫棋为你唱歌...."); } public void dance() { System.out.println("邓紫棋为你跳艳舞...."); } }
4. 代理对象也不用实现接口
//代理对象 精济人 public class DengziqiProxy implements MethodInterceptor{ //邓紫棋来了. 维护目标对象 private Object target; public DengziqiProxy(Object target){ this.target = target; } //给目标对象创建代理对象 public Object getDengziqiProxy(){ // 获得代理对象,也指向了接口. Enhancer enhancer = new Enhancer();// 工具类 enhancer.setSuperclass(target.getClass()); //设置父类 enhancer.setCallback(this); //设置回调函数 return enhancer.create();//创建子类(代理对象) } @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { System.out.println("dengziqi is coming"); Object result = method.invoke(target, args); System.out.println("so cool..."); return result; } }
5. 测试
// 测试类 public class ProxyTests { public static void main(String[] args) { //1. 先目标对象 Dengziqi dengziqi = new Dengziqi(); //邓紫棋找来了 System.out.println(dengziqi.getClass()); // class com.vn.copy.DengziqiImpl //2. 代理对象 Dengziqi dengziqiProxy = (Dengziqi) new DengziqiProxy(dengziqi).getDengziqiProxy(); System.out.println(dengziqiProxy.getClass()); // class com.vn.copy.DengziqiImpl$$EnhancerByCGLIB$$34a5605e dengziqiProxy.sing(); //审核条件达标者, 通过,让邓紫棋唱歌 dengziqiProxy.dance();//审核条件达标者, 通过,让邓紫棋跳舞 /* dengziqi is coming 邓紫棋为你唱歌.... so cool... dengziqi is coming 邓紫棋为你跳艳舞.... so cool...*/ } }