动态代理源码分析

使用

  • 说起动态代理,大家都不陌生,但对其原理却一知半解。经常遇到一个问题,java动态代理为何只能适用接口,why?你有考虑过其底层逻辑原因吗?
  1. 首先看一个简单的使用
public class MyInvocationHandler implements InvocationHandler {

    private Object target ;

    public MyInvocationHandler(Object target) {
        super();
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 在目标对象的方法执行之前简单的打印一下
        System.out.println("------------------before------------------");

        // 执行目标对象的方法
        Object result = method.invoke(target, args);

        // 在目标对象的方法执行之后简单的打印一下
        System.out.println("-------------------after------------------");

        return result;
    }


    /**
     * 获取目标对象的代理对象
     * @return 代理对象
     */
    public Object getProxy() {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                target.getClass().getInterfaces(), this);
    }
}
  1. 以上,主要看Proxy.newProxyInstance代理方法
    • java对象创建过程,一般都是创建.java类通过javac编译成.class文件,通过类加载器创建对象初始化;


      image
public static Object newProxyInstance(ClassLoader loader,
                                      Class<?>[] interfaces,
                                      InvocationHandler h){
        
    //获得class对象 cl为 $Proxy0
    Class<?> cl = getProxyClass0(loader, intfs);
    
    //获取构造函数
    final Constructor<?> cons = cl.getConstructor(constructorParams);
    final InvocationHandler ih = h;
    if (!Modifier.isPublic(cl.getModifiers())) {
        AccessController.doPrivileged(new PrivilegedAction<Void>() {
            public Void run() {
                cons.setAccessible(true);
                return null;
            }
        });
    }
    //根据构造函数反射调用初始化对象,注意里面的h为实现MyInvocationHandler传入的this
    return cons.newInstance(new Object[]{h});
                                          
}
  • 那么动态代理是如何创建代理对象呢?我们分析以上代码可知:
    1. newProxyInstance中getProxyClass0()获取代理的.class文件,这里没有了.java源码,而是直接生成class文件,通过class创建对象;
    2. 有class文件后调用newInstance创建对象,注意构造函数中传入参数h为实现InvocationHandler
  1. 进入getProxyClass0方法,记得参数loader : 类加载器, interfaces当前需要代理的接口数据
private static Class<?> getProxyClass0(ClassLoader loader,
                                           Class<?>... interfaces) {
    
        return proxyClassCache.get(loader, interfaces);
}

public V get(K key, P parameter) {
       
        //从缓存中获取,首次肯定没有的
        ......

        // 创建类对象subKeyFactory在WeakCache初始化传入
        Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
        Supplier<V> supplier = valuesMap.get(subKey);
        
    }

//Proxy中初始化缓存WeakCache
private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
        proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());

  • 肯定有个缓存快速查找啦,没有就通过subKeyFactory.apply工厂类去新建啦!
  1. 以上subKeyFactory.apply对应的为ProxyClassFactory类中的apply方法: 生成代理类$Proxy0的class文件并返回
public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {

            Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
            for (Class<?> intf : interfaces) {
                /*
                 * Verify that the class loader resolves the name of this
                 * interface to the same Class object.
                 */
                Class<?> interfaceClass = null;
                try {
                    interfaceClass = Class.forName(intf.getName(), false, loader);
                } catch (ClassNotFoundException e) {
                }
                if (interfaceClass != intf) {
                    throw new IllegalArgumentException(
                        intf + " is not visible from class loader");
                }
                /*
                 * 如果当前不是接口,抛出异常,但是并未说明我们的疑问
                 */
                 
                if (!interfaceClass.isInterface()) {
                    throw new IllegalArgumentException(
                        interfaceClass.getName() + " is not an interface");
                }
                /*
                 * Verify that this interface is not a duplicate.
                 */
                if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
                    throw new IllegalArgumentException(
                        "repeated interface: " + interfaceClass.getName());
                }
            }

            String proxyPkg = null;     // package to define proxy class in
            int accessFlags = Modifier.PUBLIC | Modifier.FINAL;

            /*
             * Record the package of a non-public proxy interface so that the
             * proxy class will be defined in the same package.  Verify that
             * all non-public proxy interfaces are in the same package.
             */
            for (Class<?> intf : interfaces) {
                int flags = intf.getModifiers();
                if (!Modifier.isPublic(flags)) {
                    accessFlags = Modifier.FINAL;
                    String name = intf.getName();
                    int n = name.lastIndexOf('.');
                    String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
                    if (proxyPkg == null) {
                        proxyPkg = pkg;
                    } else if (!pkg.equals(proxyPkg)) {
                        throw new IllegalArgumentException(
                            "non-public interfaces from different packages");
                    }
                }
            }

            if (proxyPkg == null) {
                // if no non-public proxy interfaces, use com.sun.proxy package
                proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
            }

            /*
             * 创建类名 $proxy + num自增加作为proxyName类名 .class
             */
            long num = nextUniqueNumber.getAndIncrement();
            String proxyName = proxyPkg + proxyClassNamePrefix + num;

            /*
             * 生成类名class的byte数组
             */
            byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
                proxyName, interfaces, accessFlags);
            try {
                //native生成字节码文件
                return defineClass0(loader, proxyName,
                                    proxyClassFile, 0, proxyClassFile.length);
            } catch (ClassFormatError e) {
                /*
                 * A ClassFormatError here means that (barring bugs in the
                 * proxy class generation code) there was some other
                 * invalid aspect of the arguments supplied to the proxy
                 * class creation (such as virtual machine limitations
                 * exceeded).
                 */
                throw new IllegalArgumentException(e.toString());
            }
        }
    }
  • 生成class文件格式步骤为:
    1. 首先验证是否时接口,这里只是验证代理必须是接口,至于为何这里没有显示哦;
    2. 创建.class文件的类名为$Proxy自增的num,首次为0,这个我们待会可以看到的
    3. 通过ProxyGenerator.generateProxyClass生成byte数组后通过调用native方法defineClass0生成class文件
  1. 返回的为$Proxy0类
    1. 还记得2中cons.newInstance(new Object[]{h}),有上面class生成可知cons即为$Proxy0调用 newInstance构造函数传参为 h即 Proxy.newProxyInstance()中第三个参数h实现InvocationHandler的对象
    2. super(var1)将h传给$Proxy0父类Proxy的h,因此可知$Proxy0中所调用的super.h即为我们自己写的实现InvocationHandler的对象(很多地方用的是匿名内部类)
public final class $Proxy0 extends Proxy implements UserService {
    //构造函数中传入的var1即为上方的h,super即为Proxy
    public $Proxy0(InvocationHandler var1) throws  {
        super(var1);
    }
        
    //父类中的Proxy构造函数h = MyInvocationHandler
    protected Proxy(InvocationHandler h) {
        Objects.requireNonNull(h);
        this.h = h;
    }
}
  • 以上分析为何动态代理只适用于接口,看我们生成的$Proxy0 必须要extends Proxy,而由于java的单继承原则,因此不能在继承类了,只能实现接口,因此只适用与接口;
  1. newProxyInstance返回的为代理生成class类的代理对象 $Proxy0后,调用add方法
    • $Proxy0.add() -> h为MyInvocationHandler.invoke()方法,将m3即接口方法m3 = Class.forName("test.UserService").getMethod("add"),在invoke方法中通过方式method.invoke() == m3.invoke(target , args) , result为方法返回值
public final void add() throws  {
    try {
        //h为MyInvocationHandler 调用其invoke方法
        super.h.invoke(this, m3, (Object[])null);
    } catch (RuntimeException | Error var2) {
        throw var2;
    } catch (Throwable var3) {
        throw new UndeclaredThrowableException(var3);
    }
}
  1. 通过以上调用了代理类中的invoke
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    // 在目标对象的方法执行之前简单的打印一下
    System.out.println("------------------before------------------");

    // 执行目标对象的方法,result为方法的返回值
    Object result = method.invoke(target, args);

    // 在目标对象的方法执行之后简单的打印一下
    System.out.println("-------------------after------------------");

    return result;
}
  • 注意:这里的invoke是被$Proxy0代理类调用的,参数method为$Proxy0代理类中静态变量,在invoke中调用method.invoke即反射调用实现接口类的方法,以上即为代理的完善源码分析!
  • 后续:遇到一个有趣的问题,好奇打印了一下被代理对象和代理类Proxy0,发现他们的地址也就是hashCode值是相同的,why?因为Proxy0重写了toString()方法并反射调用了被代理类的toString(),因此两者打印的完全一致!遇到不理解的,还是得多多看源码呀!
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,491评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,856评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,745评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,196评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,073评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,112评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,531评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,215评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,485评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,578评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,356评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,215评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,583评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,898评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,497评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,697评论 2 335