java基础回顾:动态代理的最感性源码解释

java基础回顾:动态代理的最感性源码解释_第1张图片
爱情呼叫

前言##

动态代理,就是在程序运行的时候,才自动生成动态代理的字节码class文件,并且利用这个class文件new出一个代理对象,进行代理的工作。动态代理的特别之后在于他在程序运行的时候才生成class文件,而普通的java用法是在编译的时候生成class文件(利用javac命令进行编译.java后缀源文件为.class后缀的字节码文件)。

目录##

1.源码跟踪
2.字节码保存并反编译
3.手写动态代理类

源码跟踪####

上一篇文章简单回顾了下java动态代理的使用,这一节从源码分析动态代理的实现
java基础回顾:动态代理 http://www.jianshu.com/p/6272658d1683

import java.lang.reflect.Proxy;

public class ShenZhen {

    public static void main(String[] args) {
        Landlord wangjianlin=new Landlord();  //实例化大富豪王健林
        Business mmAgency = (Business)Proxy.newProxyInstance(Business.class.getClassLoader(), wangjianlin
                .getClass().getInterfaces(), new AgencyHandler(wangjianlin));  //实例化中介mm

        System.out.println(mmAgency.getClass().getName());
        mmAgency.sell();   //mm开始卖房

    }
}

上一篇我们通过Proxy.newProxyInstance生成了动态代理对象mmAgency(中介小妹妹) ,但作为开发人员,看不到这个动态代理对象的源码是很痛苦的一件事。这些文章将带你看看这个动态代理对象的源码,哈哈哈!!是不是有点小期待?

首先我们从jdk的源码出发看看这个动态代理对象是如何生成的
进入Proxy类的newProxyInstance方法看看

    @CallerSensitive
    public static Object newProxyInstance(ClassLoader loader,
                                          Class[] interfaces,
                                          InvocationHandler h)
        throws IllegalArgumentException
    {
         .....
        Class cl = getProxyClass0(loader, intfs);   //获取动态生成的代理类
        final Constructor cons = cl.getConstructor(constructorParams); //获取代理类的构造方法
        return cons.newInstance(new Object[]{h});    //根据构造方法生成一个代理对象
        .....
    }

可以看到,关键点是如何获取动态生成的代理类getProxyClass0(loader, intfs)

    private static final WeakCache[], Class>
        proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());

    private static Class getProxyClass0(ClassLoader loader,
                                           Class... interfaces) {
        if (interfaces.length > 65535) {
            throw new IllegalArgumentException("interface limit exceeded");
        }
        return proxyClassCache.get(loader, interfaces);  //返回代理类
    }

最后会进入ProxyClassFactory的apply方法

        public Class apply(ClassLoader loader, Class[] interfaces) {
           .....
            //生成字节码
            byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
                proxyName, interfaces, accessFlags);
           .....

    }

所以,最后的最后,会调用ProxyGenerator.generateProxyClass方法来生成一个动态代理字节码文件。

字节码保存并反编译####

为了能够摸得到这个动态字节码文件,我们来保存下字节码文件到F盘中,运行下面的代码,就会在F盘生成$Proxy0.class字节码文件了,主要原理是调用上面说到ProxyGenerator.generateProxyClass("$Proxy0", Landlord.class.getInterfaces()); 方法,表示生成Landlord类的动态代理。

import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Proxy;
import sun.misc.ProxyGenerator;

public class GenerateProxy{

    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        byte[] classFile = ProxyGenerator.generateProxyClass("$Proxy0", Landlord.class.getInterfaces());      
        FileOutputStream out = null;      
        try {
            out = new FileOutputStream("F:/$Proxy0.class");
            out.write(classFile);
            out.flush();
            System.out.println("flush");
        } catch (Exception e) {
            System.out.println("exception");
            e.printStackTrace();
        } finally {
            try {
                out.close();
                System.out.println("close");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

注意上面的代码可能import sun.misc.ProxyGenerator;会提示错误,这个包默认是不可access的,可以参照下面的博客进行配置
http://blog.csdn.net/lixiaoxiong55/article/details/50096709

最后,我们会在F盘生成字节码文件$Proxy0.class

java基础回顾:动态代理的最感性源码解释_第2张图片
字节码文件.png

然后我们对这个字节码进行反编译,推荐一个在线反编译网站,上传$Proxy0.class文件进行反编译
http://www.ludaima.cn/java.html

java基础回顾:动态代理的最感性源码解释_第3张图片
反编译结果.png

反编译生成的代码如下,其中我把一些无用的方法去掉了,什么tostring,equal的定义都去掉了,辣眼睛

// The Decompiled time:2017-02-21 13:03:03
// Decompiled home page: http://www.ludaima.cn
// Decompiler options: packimports(3) deadcode fieldsfirst ansi space
 
import java.lang.reflect.*;
 
public final class $Proxy0 extends Proxy
    implements Business
{
 
    private static Method m1;
    private static Method m2;
    private static Method m3;
    private static Method m4;
    private static Method m0;
 
    public $Proxy0(InvocationHandler invocationhandler)
    {
        super(invocationhandler);
    }
 

    public final void sell()
    {
        try
        {
            super.h.invoke(this, m3, null);
            return;
        }
        catch (Error _ex) { }
        catch (Throwable throwable)
        {
            throw new UndeclaredThrowableException(throwable);
        }
    }
 
    static
    {
        try
        {
            m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] {
                Class.forName("java.lang.Object")
            });
            m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
            m3 = Class.forName("Business").getMethod("sell", new Class[0]);
            m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
        }
        catch (NoSuchMethodException nosuchmethodexception)
        {
            throw new NoSuchMethodError(nosuchmethodexception.getMessage());
        }
        catch (ClassNotFoundException classnotfoundexception)
        {
            throw new NoClassDefFoundError(classnotfoundexception.getMessage());
        }
    }
}

可以看到这个类继承于Proxy,实现了Business的接口(代理与被代理对象的共同接口),构造方法传入了InvocationHandler ,所以可以调用到InvocationHandler 的invoke方法。重点看看这个代理类的sell()方法,可以看到它会调用到super.h.invoke(this, m3, null);方法,这里的super是Proxy类,他的类成员h就是InvocationHandler。

    public final void sell()
    {
        try
        {
            super.h.invoke(this, m3, null);
            return;
        }
        catch (Error _ex) { }
        catch (Throwable throwable)
        {
            throw new UndeclaredThrowableException(throwable);
        }
    }

所以整个动态代理过程就是在程序执行的时候新建一个动态代理字节码$Proxy0,他会传入InvocationHandler参数,在执行代理方法sell()的时候,会调用到InvocationHandler的invoke方法,进而成功的进行了代理的操作。

手写动态代理类####

最后,我们来手写动态代理的java文件,其实就是上面反编译生成的java文件

import java.lang.reflect.*;
 
public final class $Proxy0 extends Proxy
    implements Business
{
 
    private static Method m1;
    private static Method m2;
    private static Method m3;
    private static Method m4;
    private static Method m0;
 
    public $Proxy0(InvocationHandler invocationhandler)
    {
        super(invocationhandler);
    }
 

 
    public final void sell()
    {
        try
        {
            super.h.invoke(this, m3, null);
            return;
        }
        catch (Error _ex) { }
        catch (Throwable throwable)
        {
            throw new UndeclaredThrowableException(throwable);
        }
    }
 
    public final void buy()
    {
        try
        {
            super.h.invoke(this, m4, null);
            return;
        }
        catch (Error _ex) { }
        catch (Throwable throwable)
        {
            throw new UndeclaredThrowableException(throwable);
        }
    }
 

    static
    {
        try
        {
            m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] {
                Class.forName("java.lang.Object")
            });
            m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
            m3 = Class.forName("Business").getMethod("sell", new Class[0]);
            m4 = Class.forName("Business").getMethod("buy", new Class[0]);
            m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
        }
        catch (NoSuchMethodException nosuchmethodexception)
        {
            throw new NoSuchMethodError(nosuchmethodexception.getMessage());
        }
        catch (ClassNotFoundException classnotfoundexception)
        {
            throw new NoClassDefFoundError(classnotfoundexception.getMessage());
        }
    }
}

接口

public interface Business {
      public void sell();
}

地主

public class Landlord implements Business {

    public void sell () {
        System.out .println( "I am Landlord,I sell my house" );
    }

}

中介类

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class AgencyHandler implements InvocationHandler{

    private Landlord mLandlord;

    public AgencyHandler(Landlord mLandlord){
        this.mLandlord=mLandlord;
    }
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // TODO Auto-generated method stub
        System.out.println("Boss,I has find a man want you house");
       //代理做一些预处理
        method.invoke(mLandlord, args);//地主真正卖房
        System.out.println("Boss,Congralation!");  //代理处理一些后事
        return null;
    }

}

测试类

import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Proxy;
import sun.misc.ProxyGenerator;

public class ShenZhen {

    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        
        Landlord wangjianlin=new Landlord();
        
        Business mmAgency = (Business)Proxy.newProxyInstance(Business.class.getClassLoader(), wangjianlin
                .getClass().getInterfaces(), new AgencyHandler(wangjianlin));
        
        Business mmAgency=new $Proxy0(new AgencyHandler(wangjianlin));//直接new一个动态代理类
        System.out.println(mmAgency.getClass().getName());
        System.out.println(wangjianlin.getClass().getInterfaces().length);
        mmAgency.sell();
    }
}

上面的代码跟上一节的代码比较,主要是手动增加了一个类$Proxy0,修改了测试中获取动态代理的方法,直接new了一个$Proxy0类作为代理对象中介小妹妹。

所以下面两种实例化代理对象的方法效果是一致的
第一种

   Business mmAgency = (Business)Proxy.newProxyInstance(Business.class.getClassLoader(), wangjianlin
                .getClass().getInterfaces(), new AgencyHandler(wangjianlin));  //实例化中介mm

第二种

        Business mmAgency=new $Proxy0(new AgencyHandler(wangjianlin));//直接new一个动态代理类

第二种方法是为了让我们理解动态代理的过程而展示给大家的。第二种方法其实就是手动一步一步完成第一种方法的步骤,其中步骤包括:
1.生成动态代理的class文件
2.根据class文件new一个代理对象

好了,大家有空可以去试试操作一下,加深理解,实践是检验真理的唯一标准!!

你可能感兴趣的:(java基础回顾:动态代理的最感性源码解释)