动态代理类

代理的概念与作用。

     * 程序中的代理

     *      要为已存在的多个具有相同接口的目标类的各个方法增加一些系统功能

     *      例如:异常处理,日志,计算方法的运行时间,事物管理,等等

     * 编写一个与目标类具有相同接口的代理类,代理类的每个方法调用目标类的

     * 相同方法,并在调用方法时加上系统功能的代码

     * 动态代理:JVM可以在运行期动态生成出类的字节码,这种动态生成的类往往被用作代理

     * 类,即动态代理。

     * JVM生成的动态类必须实现一个或者多个接口,所以,jvm生成的动态类只能用作具有

     * 相同接口的目标类的代理。

     * CGLIB库可以动态生成一个类的子类,一个类的子类也可以用作该类的代理,所以,

     * 如果要为一个没有实现接口的类生成动态代理类,那么可以使用GCLIB库。

     * 代理类的各个方法中通常除了要调用目标的相应方法和对外返回目标返回的结果

     * 外,还可以在代理方法中的如下四个位置奖赏系统功能代码:

     * 1 在带哦用目标方法之前

     * 2 在调用目标方法之后

     * 3 在调用目标方法前后

     * 4 在处理目标方法异常的catch块中                             

Collection proxy3 = (Collection)Proxy.newProxyInstance(

              Collection.class.getClassLoader(),

              newClass[]{Collection.class},

              newInvocationHandler(){

             

传参数情况  比如调用add   因为字节码文件只有一份所以method就能转换到ArrayList

    Objectproxy = proxy3

    Methodmethod = proxy3.getClass.getMethod("add")  

    Object[]args = "aaa"

                  ArrayListtarget = new ArrayList();

                  publicObject invoke(Object proxy, Method method, Object[] args)

                         throwsThrowable {

                     longbeginTime = System.currentTimeMillis();

                     ObjectreVal = method.invoke(target, args);

                     longendTime = System.currentTimeMillis();

                     System.out.println(method.getName()+"运行时间为:"+(endTime- beginTime)+"毫秒");

                     returnreVal;  

                  }

                 

              });

       Object obj= proxy3.add("aaa")

       proxy3.add("bbb");

       proxy3.add("ccc");

       System.out.println(proxy3.size());

       /*

        *动态类内部的方法

        * class Proxy implements Collection

        * {

        *      Proxy(InvocationHandlerhandler)

        *     {

        *         this.handler= handler;

        *      }

        *      publicint size()

        *      {

               *         returnhandler.invoke(this,this.getClass.getMethod("size"),null);

        *      }

        *      publicvoid clear()

        *      {

        *                                         handler.invoke(this,this.getClass.getMethod("clear"),null);

        *      }

        *      publicboolean add(Object[] args)

        *      {

               *         returnhandler.invoke(this,this.getClass.getMethod("add"),args);

        *      }

        *      .......

        *      .......

        *      .......

        *}   

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值