劣实基础–Java 动态代理机制

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lwj_zeal/article/details/89008713

xmind

代理模式

代理在我们日常生活中经常出现,例如我们去租房,为了方便我们会去找中介,让他们帮我去找房子,事后我们给他一定比例的中介费就可以了,这种好处就不需要我们自己去奔波租房。

在程序中也有代理这种思想,当我们想在一个已有的类的方法被调用前调用后都输出一段日志信息,而我们目前无法修改类内部的结构,但是我们可以生成一个代理对象,通过代理对象去调用目标对象的这些方法,因为目标方法会被代理对象所调用,所以在调用的前后就可以做一些我们想要加入的功能了。

下面的引入代理模式的好处:

  • 通过引入代理对象的方式来间接访问目标对象,防止直接访问目标对象给系统带来的不必要复杂性;
  • 通过代理对象对原有的业务增强;

代理模式

代理模式一般有三个角色:

  • 抽象角色

指的是真实角色代理角色对外提供的公共方法,一般会接口。

  • 真实角色

需要实现抽象角色接口,定义了真实角色所要实现的业务逻辑,以便供代理角色调用

  • 代理角色

需要实现抽象角色接口,是真实角色的代理,内部会调用真实角色业务逻辑

对于访问者不需要直接访问真实角色,只需要访问代理角色,由代理角色访问真实角色。

静态代理

静态代理在使用时,需要定义接口或者父类,被代理对象与代理对象一起实现相同的接口或者是继承相同父类。

扫描二维码关注公众号,回复: 5840582 查看本文章

在这里举两个小栗子

  • 抽象角色
public interface AppStore {
    void sale(String saleName);
}

  • 真实角色:香港 AppStore 商店
public class HKAppStore implements AppStore {
    @Override
    public void sale(String saleName) {
        System.out.println("香港 AppStore 出售" + saleName);
    }
}
  • 代理角色:专门负责去香港代购的小哥哥
public class HKAppleAgent implements AppStore {
    private AppStore appStore = null;

    public HKAppleAgent(AppStore appStore) {
        this.appStore = appStore;
    }

    @Override
    public void sale(String saleName) {
        beforeSale(saleName);
        appStore.sale(saleName);
        afterSale(saleName);
    }

    private void beforeSale(String saleName) {
        //查询美国哪里可以购买这个物品
        System.out.println("苹果代理正在网上查询哪里可以购买" + saleName);
    }

    private void afterSale(String saleName) {
        //买到物品后就打包,发送给用户
        System.out.println("苹果代理正在打包快递发送给客户");
    }
}

在我们定义好这三个角色后,接下来看一下老王和老张通过静态代理购物的事

  • 老王找香港代购一台 iPhoneX
//真实角色-HKAppStore
HKAppStore hkAppStore = new HKAppStore();
//代理角色-HKAppleAgent,持有真实角色的引用
HKAppleAgent agent = new HKAppleAgent(hkAppStore);
String saleName = "港版iPhoneX";
System.out.println("老王想找香港代购要买一个" + saleName);
//老王找到代购(代理角色)去香港买一台 iPhoneX
agent.sale(saleName);
  • 老张找代理去去华强北买一个 Sony 4K 高清电视
//真实角色-SonyTVStore
SonyTVStore sonyTVStore = new SonyTVStore();
//代理角色-华强北 Sony 电视的代理
HuaQiangBeiSonyAgent huaQiangBeiSonyAgent = new HuaQiangBeiSonyAgent(sonyTVStore);
saleName = "Sony 4K高清电视";
System.out.println("老张想找华强北道理要买一个" + saleName);
//老张找到代理购买 Sony 电视。
huaQiangBeiSonyAgent.sale(saleName);

通过上面两个简单的栗子可以看出,静态代理模式弊端是一个代理角色对应一个真实角色或者一个代理角色对应多个真实角色,而且需要事先确定好代理角色和真实角色的关系。

静态代理,一对一则会出现时静态代理对象量多、代码量大,从而导致代码复杂,可维护性差的问题,一对多则代理对象会出现扩展能力差的问题。

动态代理

是指在使用时再创建代理类实例。

动态代理的优点可以解决创建多个静态代理的问题,避免代码重复,有更高的灵活性。但其缺点是内部使用Java反射机制来间接去调用真实角色的业务逻辑。

在应用场景来说,因为 Java 类是单继承的,并且动态代理生成的代理对象是继承至 java.lang.Proxy 类,所以只能针对接口来创建代理对象,而不能通过来创建代理对象。

Proxy 与 InvocationHandler 的介绍

在 Java 动态代理机制中需要关于下面两个类:

  • java.lang.reflect.Proxy

  • java.lang.reflect.InvocationHandler

Proxy

在 Java 中已经为我们提供了生成动态代理的对象的 API 了,它就是 java.lang.reflect.Proxy。

在 JDK 文档中的介绍如下:

Proxy provides static methods for creating dynamic proxy classes and instances, and it is also the 
superclass of all dynamic proxy classes created by those methods. 

简单翻译:Proxy 提供一些静态方法去创建动态代理 Class 字节码或者动态代理对象,并且 Proxy 是所有动态代理对象的父类,这个动态的生成的代理对象是继承了 Proxy 并且实现需要代理的接口方法。

动态生成代理对象的 Class 字节码对象(麻烦)

public static Class<?> getProxyClass(ClassLoader loader,Class<?>... interfaces)throws IllegalArgumentException

通过这种方式可以动态的生成代理类的字节码对象,该方法接受的参数如下:

  • loader 表示加载代理类的类加载器,因为一个 .class 文件在被使用前需要通过类加载器进行加载到内存中成为字节码才行。
  • interfaces 代理类需要实现的接口,因为代理对象需要模拟一个跟目标对象一样的功能,因此需要实现目标类实现的接口,这样才有目标类的所有的功能,在代理方法被调用时,代理对象会将该操作分发给 InvocationHandler 去处理。
  • 返回值: 返回一个代理类的字节码对象,这个类是通过 loader 去加载的。

通过这种方式虽然获取了代理类的字节码对象,但是最终获取一个代理对象还是需要通过反射来获取到对应的对象对象。

动态生成代理对象(一步到位)

上面的方式是首先获动态代理的字节码对象,然后再通过 Constructor.newInstance(handler) 的方式来创建动态代理对象,这种方式需要两步走,稍微麻烦一些。在上面介绍 Proxy 的功能时说过它除了可以动态创建代理对象的字节码对象也可以直接创建动态代理对象

通过以下方法可以直接动态生成代理类对象,这里的参数分别表示:

static Object newProxyInstance (ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
  • loader 表示加载代理类的类加载器;
  • interfaces 代理类需要实现的接口字节码数组;
  • h 表示用于目标方法被调用时的回调;
  • 返回值: 返回一个代理对象,这个代理对象是通过 loader 去加载的,并且是通过实现了 interfaces 接口。

InvocationHandler

JDK 文档对 InvocationHandler 的描述如下:

InvocationHandler is the interface implemented by the invocation handler of a proxy instance. 
Each proxy instance has an associated invocation handler. When a method is invoked on a proxy instance, 
the method invocation is encoded and dispatched to the invoke method of its invocation handler.

InvocationHandler代理对象所实现的接口,每一个代理对象都有一个 InvocationHandler 成员变量,当代理对象的方法被调用时,该方法会将调用分发给它的成员变量 InvocationHandler 去处理。

使用动态代理改造上面的栗子

ProxyUtils 负责去生成动态队里对象的,内部持有真实角色的实例realObj,外部通过调用 getProxy(…) 即可获取指定类型的动态代理对象,外部调用动态代理对象方法时,内部会将其分发给 invoke 方法。

//ProxyUtils.java
public class ProxyUtils implements InvocationHandler {
    /*持有的真实对象*/
    public Object realObj = null;


    public Object getRealObj() {
        return realObj;
    }

    public void setRealObj(Object realObj) {
        this.realObj = realObj;
    }

    /**购买前*/
    private void beforeSale() {
        System.out.println("代理在购买前先和客户协商好价格");
    }
    /**购买后*/
    private void afterSale() {
        System.out.println("代理在购买到商品后给客户打包");
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        beforeSale();
        Object obj = method.invoke(realObj, args);
        afterSale();
        return obj;
    }

    /*通过Proxy获得动态代理对象*/
    public Object getProxy() {
        return java.lang.reflect.Proxy.newProxyInstance(realObj.getClass().getClassLoader(), realObj.getClass().getInterfaces(), this);
    }

通过 ProxyUtils 来生成对应的动态代理对象

AppStore hkAppStore = new HKAppStore();
ProxyUtils proxy = new ProxyUtils();
proxy.setRealObj(hkAppStore);
//得到 AppStore 的一个香港代理
AppStore appStoreProxy = (AppStore) proxy.getProxy();
String saleName = "港版iPhoneX";
appStoreProxy.sale(saleName);
final SonyTV sonyTVStore = new SonyTVStore();
proxy.setRealObj(sonyTVStore);
saleName = "Sony 4K高清电视";
SonyTV sonyTVProxy = (SonyTV) proxy.getProxy();
sonyTVProxy.sale(saleName);

通过上面的改造后,并不需要像静态代理那样需要实现创建好代理对象,这一步是在运行时创建,只要你传给我一个真实角色对象,我的 ProxyUtils#getProxy() 内部就会去帮你生成一个代理对象为你服务。

Proxy 工作原理

现在我们只会使用 JDK 为我们提供的 Proxy 去生成动态代理来玩,但是它内部是如何实现动态代理对象的,我相信目前你是比较好奇的,下面来一步步的分析 Proxy 的工作原理。

  • 入口 Proxy.newProxyInstance(…)
//Proxy.java
public static Object newProxyInstance(ClassLoader loader,
                                      Class<?>[] interfaces,
                                      InvocationHandler h){
    
    //①
    Class<?> cl = getProxyClass0(loader, intfs);
    
    try {
        //②
        final Constructor<?> cons = cl.getConstructor(constructorParams);
        final InvocationHandler ih = h;
        //③
        return cons.newInstance(new Object[]{h});
    } catch (NoSuchMethodException e) {
        throw new InternalError(e.toString(), e);
    }
}

我们对 newProxyInstance(…)类的代码做了一些删减,得到以下三个核心点。①根据传入的参数得到一个 cl 对象,这个对象就是动态代理类的 Class 字节码对象了,在②处通过反射得到 Constructor 对象,然后在③处根据得到的 Constructor 对象实例化这个动态代理对象。

这里比较核心代码就是分析①处是如何得到代理类的 Class 对象的。

  • getProxyClass0(…)
//Proxy.java   
private static Class<?> getProxyClass0(ClassLoader loader,
                                       Class<?>... interfaces) {
    //①                                    
    if (interfaces.length > 65535) {
        throw new IllegalArgumentException("interface limit exceeded");
    }
    //②
    return proxyClassCache.get(loader, interfaces);
}


/**
* a cache of proxy classes
*/
//缓存代理对象
private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
        proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());

可以看到 getProxyClass0()内部核心比较少,在①处用于判断代理对象实现的接口数量不能超过 65535 ,在②处是通过缓存 proxyClassCache 获取一个 Class 对象的。下面来看这个缓存是如何工作的。

  • proxyClassCache.get(…)

在这里 proxyClassCache 内部经过多次辗转会走到 ProxyClassFactory#apply 去生成对应的 Class 对象。

//Proxy.java
private static final class ProxyClassFactory
    implements BiFunction<ClassLoader, Class<?>[], Class<?>>
{
    // prefix for all proxy class names
    private static final String proxyClassNamePrefix = "$Proxy";
    // next number to use for generation of unique proxy class names
    private static final AtomicLong nextUniqueNumber = new AtomicLong();
    @Override
    public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {
        ...    
        /*
         * Choose a name for the proxy class to generate.
         */
        //$Proxy0,$Proxy1 这个 num 就是表示这个类名的这个数字
        long num = nextUniqueNumber.getAndIncrement();
        //①得到类名:包名.$Proxy+num
        String proxyName = proxyPkg + proxyClassNamePrefix + num;
        /*
         * Generate the specified proxy class.
         */
        //②
        byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
            proxyName, interfaces, accessFlags);
        try {
            //③
            return defineClass0(loader, proxyName,
                                proxyClassFile, 0, proxyClassFile.length);
        } catch (ClassFormatError e) {
            throw new IllegalArgumentException(e.toString());
        }
    }
}

在ProxyClassFactory内部剔除一些代码后,主要是做以下几件事:

  • 在①处确定要生成的类的名字;
  • 在②通过 ProxyGenerator类 去生成对应的代理对象字节码 byte[] 数组
  • 在③通过 defineClass0 类加载器去加载这个 byte[] 表示的代理对象到内存中。

都这里,我们就知道 JDK 内部其实就是通过 ProxyGenerator 这个类去生成一个动态代理类的byte[] 数组。ProxyGenerator 内部如何实现我们就不跟进去看的。

动态代理类名字 $Proxy0 验证

下面我来实地验证一下代理类的名字,我们在得到代理对象处打一个断点:

在这里就印证了上面的类名的定义 $Proxy0 了。

$Proxy0

保存动态代理类到磁盘中

下面通过这种ProxyGenerator来将代理对象的 byte[] 真真正正保存到本地文件中。

//ProxyUtils.java
/**
 * 在磁盘种生成代理类
 * @param proxyClazzName
 * @param clazz
 */
public static void generateProxy(String proxyClazzName, Class clazz) {
    byte[] data = ProxyGenerator.generateProxyClass(proxyClazzName, new Class[]{clazz});
    String path = clazz.getResource(".").getPath();
    ///Users/liaowj/Documents/code/study4Java/proxy/build/classes/java/main/com/example/proxy/_static/
    System.out.println(path);
    try (FileOutputStream out = new FileOutputStream(new File(path, proxyClazzName + ".class"));) {
        out.write(data);
        out.flush();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

调用

Proxy.generateProxy("ProxyTest", AppStore.class);

动态代理最终生成的路径如下:

磁盘保存动态代理类文件

最终生成的代理源码如下:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

import com.example.proxy._static.AppStore;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;

public final class AppStoreProxyTest extends Proxy implements AppStore {
    private static Method m1;
    private static Method m3;
    private static Method m2;
    private static Method m0;

    public AppStoreProxyTest(InvocationHandler var1) throws  {
        super(var1);
    }

    public final boolean equals(Object var1) throws  {
        try {
            return (Boolean)super.h.invoke(this, m1, new Object[]{var1});
        } catch (RuntimeException | Error var3) {
            throw var3;
        } catch (Throwable var4) {
            throw new UndeclaredThrowableException(var4);
        }
    }

    public final void sale(String var1) throws  {
        try {
            super.h.invoke(this, m3, new Object[]{var1});
        } catch (RuntimeException | Error var3) {
            throw var3;
        } catch (Throwable var4) {
            throw new UndeclaredThrowableException(var4);
        }
    }

    public final String toString() throws  {
        try {
            return (String)super.h.invoke(this, m2, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    public final int hashCode() throws  {
        try {
            return (Integer)super.h.invoke(this, m0, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    static {
        try {
            m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
            m3 = Class.forName("com.example.proxy._static.AppStore").getMethod("sale", Class.forName("java.lang.String"));
            m2 = Class.forName("java.lang.Object").getMethod("toString");
            m0 = Class.forName("java.lang.Object").getMethod("hashCode");
        } catch (NoSuchMethodException var2) {
            throw new NoSuchMethodError(var2.getMessage());
        } catch (ClassNotFoundException var3) {
            throw new NoClassDefFoundError(var3.getMessage());
        }
    }
}

分析 AppStoreProxyTest 代理类源码

我们一步一步的分析这个 ProxyGenerator 帮我们生成的代理类内部怎么实现代理功能的。

  • 类声明

我们前面说过,代理角色是需要实现抽象角色接口的,在这里可以看到 AppStoreProxyTest 是实现 AppStore 接口的。然后分析 Proxy 类时,我们看了该类的注释,Proxy 是所有动态代理类的父类,从下面的 AppStoreProxyTest 的继承关系也可以验证这一点了。

public final class AppStoreProxyTest extends Proxy implements AppStore {}
  • 类静态代码块

在静态代码块中,将 Object 中的 equals ,toString,hashCode 对应的 Method 对象 和抽象角色 AppStore 的接口方法的 Method 对象保存到类变量中,方便代理对象方法被调用时能一一对应到真实角色的业务方法。

static {
    try {
        m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
        m3 = Class.forName("com.example.proxy._static.AppStore").getMethod("sale", Class.forName("java.lang.String"));
        m2 = Class.forName("java.lang.Object").getMethod("toString");
        m0 = Class.forName("java.lang.Object").getMethod("hashCode");
    } catch (NoSuchMethodException var2) {
        throw new NoSuchMethodError(var2.getMessage());
    } catch (ClassNotFoundException var3) {
        throw new NoClassDefFoundError(var3.getMessage());
    }
}
  • InvocationHandler 分发

在调用动态代理对象的 sale 方法时,它内部会调用 super.h.invoke(...),这个 super.h 就是父类 ProxyInvocationHandler 属性,所以在调用动态代理方法时会将其分发Invacationhandler 去实现,在其Invacationhandler内部再去调用真实角色的业务逻辑代码。

public final void sale(String var1) throws  {
    try {
        super.h.invoke(this, m3, new Object[]{var1});
    } catch (RuntimeException | Error var3) {
        throw var3;
    } catch (Throwable var4) {
        throw new UndeclaredThrowableException(var4);
    }
}
public class Proxy{
    protected InvocationHandler h;
}

项目地址:https://github.com/liaowjcoder/study4Java/tree/master/proxy

记录于2019年4月4日凌晨

猜你喜欢

转载自blog.csdn.net/lwj_zeal/article/details/89008713
今日推荐