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();
  • 相关阅读:
    GNU Linux中的SO_RCVLOWAT和SO_SNDLOWAT说明
    Spring.NET 的IOC(依赖注入)
    c# post 数据的方法
    C# .NET中的 反射的应用
    C# .NET修改注册表
    DataTabel DataSet 对象 转换成json
    sqlserver 行转列
    asp.net 二级域名session共享
    Asp.Net集群中Session共享
    微软企业库DBBA的研究
  • 原文地址:https://www.cnblogs.com/xp2h/p/12377270.html
Copyright © 2011-2022 走看看