zoukankan      html  css  js  c++  java
  • 动态代理(二)

    书接上文: https://www.cnblogs.com/lyhero11/p/8430602.html

    最近写了一个小rpc框架,对动态代理有了新体会:

    package com.wangan.test.proxy;
    
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    
    public class CarProxy implements InvocationHandler{
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("speed或者torque测试是不可能测试的,都是不可能测试的!");
            return null;
        }
    }

    测试代码:

    CarProxy proxy = new CarProxy();
            Car car = (Car)Proxy.newProxyInstance(Car.class.getClassLoader(),
                                                     new Class[] {Car.class},
                                                     proxy);
            car.speed();
            car.torque();

    其中Car接口与上一篇中的一样,但是本次这里没有实现类!

    运行结果:

    speed或者torque测试是不可能测试的,都是不可能测试的!
    speed或者torque测试是不可能测试的,都是不可能测试的!

    也就是说,基于某一个实现了Car接口的被代理对象(比如LancerEvolutionVI)生成一个InvocationHandler对象,从而生成代理对象,可以去实现方法的AOP;

    也可以像本篇这样,完全基于Car接口去生成InvocationHandler对象(InvocationHandler里没有被代理对象方法的实现),也可以生成代理对象!

    总结:

    使用Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)生成代理对象,三个参数分别是代理对象的需要的classloader(一般是被代理对象或者其接口的loader),代理对象需要implements的interface(一般也是被代理对象的interface),以及一个InvocationHandler;

    在InvocationHandler里Override invoke方法,拿到被代理对象的method对象,做aop,或者相当于直接实现重写方法。

  • 相关阅读:
    python -- 面向对象
    python应用----函数
    python
    python 基础应用5-简单购物车
    python 基础知识5-集合
    python 基础应用4
    python 基础知识4
    python 基础知识3-列表元祖
    python 基础应用3
    无法进入局域网远程桌面--Windows防火墙设置
  • 原文地址:https://www.cnblogs.com/lyhero11/p/10370750.html
Copyright © 2011-2022 走看看