动态代理(二)

书接上文: 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,或者相当于直接实现重写方法。

原文地址:https://www.cnblogs.com/lyhero11/p/10370750.html