zoukankan      html  css  js  c++  java
  • cgli动态代理

     1 /**
     2  * Cglib 动态代理
     3  * 1.引入cglib-nodep-2.2.jar 依赖
     4  * 2.实现MethodInterceptor 接口
     5  * 3.创建一个代理对象
     6  * 4.完成 intercept方法
     7  */
     8 public class CgilbProxy implements MethodInterceptor {
     9     /**
    10      * 返回一个代理对象
    11      * @param classes
    12      * @return
    13      */
    14     public Object getInstance(Class<?> classes){
    15         // 通过Enhancer创建一个代理类
    16         Enhancer enhancer = new Enhancer();
    17         enhancer.setSuperclass(classes);
    18         enhancer.setCallback(this);
    19 
    20         //创建一个代理对象
    21         return enhancer.create();
    22     }
    23     /**
    24      * 返回一个代理对象
    25      * @param o
    26      * @param method
    27      * @param objects
    28      * @param methodProxy
    29      * @return
    30      * @throws Throwable
    31      */
    32     @Override
    33     public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
    34         //proxy  是上个方法的代理对象
    35         //method 调用的方法
    36         //args  返回参数
    37         System.out.println("代理的方法"+ method.getName());
    38         Object result = methodProxy.invokeSuper(o, objects);
    39         
    40         return result;
    41     }
    42 }
    //卖车
    public interface  sellCar {
        void sellcar();
    
    }
    //经理卖车
    public class Manage implements sellCar {
        @Override
        public void sellcar() {
            System.out.println("卖车");
        }
    }
    public class Client {测试// 创建代理对象  代理接口
        public static void main(String[] args) {
            CgilbProxy cgilbProxy = new CgilbProxy();
            sellCar  instance = (sellCar) cgilbProxy.getInstance(Manage.class);
            instance.sellcar();
        }
    }

    上面是通过接口

    -----------------

    下面的例子是通过类

    public class Manage  {
        public void sellcar() {
            System.out.println("卖车");
        }
    }
        public static void main(String[] args) {测试
            CgilbProxy cgilbProxy = new CgilbProxy();
    
            Manage manage= (Manage) cgilbProxy.getInstance(Manage.class);
            manage.sellcar();
        }
  • 相关阅读:
    poj 2312 Battle City
    poj 2002 Squares
    poj 3641 Pseudoprime numbers
    poj 3580 SuperMemo
    poj 3281 Dining
    poj 3259 Wormholes
    poj 3080 Blue Jeans
    poj 3070 Fibonacci
    poj 2887 Big String
    poj 2631 Roads in the North
  • 原文地址:https://www.cnblogs.com/rzkwz/p/12656070.html
Copyright © 2011-2022 走看看