• 动态代理模式


     想实现动态代理就的用一个类实现(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类实现了此接口。

  • 相关阅读:
    LOJ#2244 起床困难综合症
    CF集萃2
    LOJ#2085 循环之美
    LOJ#2087 国王饮水记
    LOJ#2304 泳池
    人生中十个重要的健康伴侣
    web容器和servlet容器
    有关服务器,web 服务器,WEB容器的一点总结
    学习Java需要达到的25个目标
    EJB 规范
  • 原文地址:https://www.cnblogs.com/sanhuan/p/4027561.html
Copyright © 2020-2023  润新知