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();
  • 相关阅读:
    linux常用命令-新手入门
    centos-1908安装步骤
    存储过程和函数的一些范例
    在iis7上如何配置来看到asp报错
    如何在ashx页面获取Session值
    SQL--create Table
    NET内存持续增长问题排查
    Socket之服务调用
    编程心得
    vs中无法查找或打开PDB文件
  • 原文地址:https://www.cnblogs.com/xp2h/p/12377270.html
Copyright © 2011-2022 走看看