zoukankan      html  css  js  c++  java
  • Java 动态代理实现

    1、依赖

      java.lang.reflect.Proxy  -  提供了静态方法去创建动态代理类的实例;

      Interface InvocationHandler  -  一个代理实例调用处理程序实现的接口

    2、编写代理实例处理类

    public class InvocationHandlerProxy implements InvocationHandler {
        //被代理的接口
        private Object target;
    
        //获取代理角色
        public void setTarget(Object target){
            this.target = target;
        }
    
        //获得一个代理类
        public Object getProxy(){
            return Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
        }
    
        //处理代理实例,并返回结果
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            log();
            Object o = method.invoke(this.target, args);
            return o;
        }
    
        private void log(){
            System.out.println("执行前日志");
        }
    }

    3、测试

    //真实角色-被代理对象
            Landlord landlord = new Landlord();
            //实例化代理实例类
            InvocationHandlerProxy handlerProxy = new InvocationHandlerProxy();
            //设置要代理的对象
            handlerProxy.setTarget(landlord);
            //生成代理类InvocationHandlerProxy,以被代理对象的接口强转
            Sent proxy = (Sent) handlerProxy.getProxy();
            //代理真实操作
            proxy.rest();
  • 相关阅读:
    Hznu_0j 1533 计算球体积(水)
    电子警察
    UVA ——利用常量数组
    排序算法
    分解质因数
    几种数
    动态规划
    C. The Football Season (枚举) ( Codeforces Round #592 (Div. 2) )
    Fibonacci前n项和 (矩阵乘)
    2153: D.ly的排队问题 (拓扑排序)(vector , set , priority_queue )
  • 原文地址:https://www.cnblogs.com/xp2h/p/12377270.html
Copyright © 2011-2022 走看看