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

     想实现动态代理就的用一个类实现(implements)一个InvocationHandler接口,此接口中有个方法

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

    这个方法中接收有被代理类的方法method和方法的参数args,代理类。

      Proxy 类用来创建动态代理类和实例的静态方法。有个方法将调用invoke()方法

    可直接用 

    static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
    public static Object newProxyInstance(ClassLoader loader,  //我要代理的类的类加载   xx.getClass().getClassLoader()

    Class<?>[] interfaces, //我要代理的类,让我要实现的接口  xx.getClass().getInterfaces()
    InvocationHandler h  
    ) throws IllegalArgumentException

    代码:

    public class MyProxy implements InvocationHandler{
    private Object iu; //我要代理的类对象 ,所有类型
    public MyProxy(Object iu) { //传入被代理的类实例
    this.iu = iu;
    }
    public Object getProxy(){ //返回我(代理类)的实例 是一个接口类 要用接口接收
    return Proxy.newProxyInstance(
    this.iu.getClass().getClassLoader(), //我要代理的类的类加载
    this.iu.getClass().getInterfaces(),//我要代理的类,让我要实现的接口
    this); //我要执行的代理类中的invoke()方法
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
    throws Throwable {
    System.out.println("开始代理");
    method.invoke(this.iu, args); //调用被代理的类中的方法
    return null;
    }
    }

    test:

    public static void main(String[] args) {
    MyProxy m = new MyProxy(new UserImpl());
    IUser u = (IUser) m.getProxy();

    u.print(); //调用无参方法

    u.xx("sdfsdfsdf");//调用有参方法
    }

    IUser 为接口其中有多个方法  UserImpl类实现了此接口。

  • 相关阅读:
    寒假学习报告05
    寒假学习报告04
    微信推送信息,支付宝支付接口
    Vue组件生成依赖文件,contentype
    redis之列表字典操作
    drf版本控制redis基础
    drf分页器,url控制器,解析器,响应器
    drf认证权限频率
    drf视图认证组件
    drf序列化组件
  • 原文地址:https://www.cnblogs.com/sanhuan/p/4027561.html
Copyright © 2011-2022 走看看