动态代理
前面讲了静态代理,有明显的缺陷。。动态代理可以解决代理对象不需要实现接口的情况,但是必须要求目标对象应该有实现的接口,才能用动态代理对功能进行扩展
接口类 IStudent
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package cn.secol.dynamic_proxy; 2 3 public interface IStudent { 4 void learn(); 5 }
目标对象类StudentImp
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package cn.secol.dynamic_proxy; 2 /** 3 * 目标对象 4 * @author Administrator 5 * 6 */ 7 public class StudentImp implements IStudent { 8 9 @Override 10 public void learn() { 11 System.out.println("演示动态代理"); 12 } 13 14 }
代理对象ProxyFactory
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package cn.secol.dynamic_proxy; 2 3 import java.lang.reflect.InvocationHandler; 4 import java.lang.reflect.Method; 5 import java.lang.reflect.Proxy; 6 7 public class ProxyFactory { 8 //维护一个目标对象 9 private Object target; 10 11 public ProxyFactory(Object target) { 12 this.target = target; 13 } 14 public Object getProxyInstance(){ 15 return Proxy.newProxyInstance( 16 target.getClass().getClassLoader(),//类加载器 17 target.getClass().getInterfaces(),//接口类型 18 new InvocationHandler() { 19 20 @Override 21 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 22 System.out.println("处理前code###"); 23 24 Object returnValue = method.invoke(target, args); 25 26 System.out.println("处理后code###"); 27 return returnValue; 28 } 29 }); 30 } 31 }
测试类TestDemo
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package cn.secol.dynamic_proxy; 2 3 import org.junit.Test; 4 5 /** 6 * 测试类 7 * @author Administrator 8 * 9 */ 10 public class TestDemo { 11 12 @Test 13 public void fun1(){ 14 //创建目标对象 15 IStudent stu = new StudentImp(); 16 //创建代理对象 17 IStudent proxy = (IStudent) new ProxyFactory(stu).getProxyInstance(); 18 proxy.learn(); 19 } 20 }
运行结果:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
posted on 2017-11-17 13:35 OrangeCsong 阅读(139) 评论(0) 编辑 收藏 举报