SSM(6)-动态代理-InvocationHandler-Proxy

承接上篇
动态的是什么:1. 被代理的对象  Object target
                          2.处理的方法  method.getName()
InvocationHandler         Proxy
实现步骤:
1.写一个handler用来处理被代理对象,分4步html

public class ProxyInvocationHandler implements InvocationHandler {

    //1.被代理的接口 从具体到抽象的过程

    private Object target;
    public void SetTarget(Object target)
    {
        this.target=target;
    }

    //2.生成代理类
    public Object getProxy()
    {
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),
               target.getClass().getInterfaces(),this);
  
    }

    //3.处理代理实例,并返回结果
   // proxy : 代理类
   // method : 代理类的调用处理程序的方法对象.
   public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
       log(method.getName());
       Object result = method.invoke(target, args);
       return result;
  }
    //4.处理的方法
    public void log(String msg)
    {
        System.out.println("执行了"+msg+"方法");
    }

}


2.写一个测试类
 java

public void mytest(){
      UserServiceImpl userService =new UserServiceImpl();
       //代理调用处理程序
       ProxyInvocationHandler pih =new ProxyInvocationHandler();
       //设置要代理的对象
       pih.SetTarget(userService);
       //动态生成代理类
       UserService proxy=(UserService) pih.getProxy();
       proxy.delete();
}