public class MyInvocationHandler implements InvocationHandler {

   

     // 目标对象  

    private Object target

     

    /**

    * 构造方法

    * @param target 目标对象 

    */ 

    publicMyInvocationHandler(Object target) { 

       super(); 

       this.target = target; 

   } 

 

 

    /**

    * 执行目标对象的方法

    */ 

    public Object invoke(Objectproxy, Method method, Object[] args) throws Throwable { 

         

       // 在目标对象的方法执行之前简单的打印一下 

       System.out.println("------------------before------------------"); 

         

       // 执行目标对象的方法 

       Object result = method.invoke(target, args); 

         

       // 在目标对象的方法执行之后简单的打印一下 

       System.out.println("-------------------after------------------");  

         

       return result; 

   } 

 

    /**

    * 获取目标对象的代理对象

    * @return代理对象

    */ 

    public Object getProxy(){ 

       return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),  

                target.getClass().getInterfaces(),this); 

   } 

 

}

***********************************************************************


 

 

publicinterface UserService {

       /**

    * 目标方法 

    */ 

    publicabstractvoid add(); 

 

}

******************************************************************

 

publicclass UserServiceImpl implements UserService {

 

     

    @override

    publicvoid add() { 

       System.out.println("--------------------add---------------"); 

   } 

}

**************************************************************

 

publicclass ProxyTest {

   

      @Test 

        publicvoid testProxy() throws Throwable { 

            // 实例化目标对象 

            UserService userService = newUserServiceImpl(); 

             

            // 实例化InvocationHandler 

            MyInvocationHandler invocationHandler =newMyInvocationHandler(userService); 

             

            // 根据目标对象生成代理对象 

            UserService proxy = (UserService)invocationHandler.getProxy(); 

             

            // 调用代理对象的方法 

            proxy.add(); 

             

        } 

 

}