动态代理的好处是实现阶段不关心代理的对象。Spring的AOP就是用动态代理来实现的。

   动态代理类要实现InvocationHandler接口

  1. public class MyProxy implements InvocationHandler { 
  2.  
  3.     Object obj = null
  4.      
  5.     public MyProxy(Object o){ 
  6.         obj = o; 
  7.     } 
  8.     @Override 
  9.     public Object invoke(Object proxy, Method method, Object[] args) 
  10.             throws Throwable { 
  11.         //before 
  12.         System.out.println("before"); 
  13.          
  14.         method.invoke(obj, args); 
  15.          
  16.         //after 
  17.         System.out.println("after"); 
  18.         return null
  19.     } 
  20.  

可以在方法执行前后进行其它操作,就是实现AOP了。

被代理的对象:

  1. public interface IReq { 
  2.  
  3.     void test(); 
  4.  
  5. public class ObjReq implements IReq { 
  6.  
  7.     @Override 
  8.     public void test() { 
  9.         System.out.println("test"); 
  10.  
  11.     } 
  12.  

 

测试:

  1. public class Client { 
  2.  
  3.     /** 
  4.      * @param args 
  5.      */ 
  6.     public static void main(String[] args) { 
  7.          
  8.         ObjReq req = new ObjReq(); 
  9.         InvocationHandler handler = new MyProxy(req); 
  10.          
  11.         IReq proxy = (IReq)java.lang.reflect.Proxy.newProxyInstance( 
  12.                 req.getClass().getClassLoader(),  
  13.                 new Class[]{IReq.class},  
  14.                 handler); 
  15.          
  16.         proxy.test(); 
  17.     } 
  18.  

用反射的方法来实现动态代理,输出结果:

before

test

after