zoukankan      html  css  js  c++  java
  • Java--JDK动态代理核心源码解析

    1、首先我们了解一下JDK动态代理的使用方法:

        public static void main(String[] args) {
            /**
             * 创建一个Bean对象,该对象实现BeanInterFace接口
             */
            BeanInterFace bean = new Bean();
    
            /**
             * 创建一个MyProxy对象,该对象实现InvocationHandler接口,将bean注入到MyProxy中
             */
            InvocationHandler invocationHandler = new MyProxy(bean);
    
            /**
             * 调用JDK的Proxy类,使用newProxyInstance方法,直接生成Bean对象的代理对象
             * 注意:Classloader必须采用实际代理对象的ClassLoader,否则会出现反复调用的问题
             */
            BeanInterFace beanProxy = (BeanInterFace) Proxy.newProxyInstance(bean.getClass().getClassLoader(),
                    bean.getClass().getInterfaces(),invocationHandler);
    
            /**
             * 使用代理对象
             */
            System.out.println(beanProxy.getClass().getName());
            beanProxy.say();
        }

    2、我们看一下JDK源码,是如何实现动态代理的

    Proxy.newProxyInstance最终会调用Proxy.ProxyClassFactory.apply()方法生成代理Class

             //创建proxyname,通过package+ClassName+编号
            String proxyName = proxyPkg + proxyClassNamePrefix + num; /* * 这里生成了代理的Class,并编译返回二进制byte[]数组 */ byte[] proxyClassFile = ProxyGenerator.generateProxyClass( proxyName, interfaces, accessFlags); try {
    //这里加载了ProxyClass,这里的加载用的是系统appClassLoader,至今我还没明白怎么才能使用,JDK使用的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()); }

    3、具体proxyClass是如何生成的

    大致就是:

    proxyClass有一个构造函数,该构造函数的参数为InvocationHandler接口,proxyClass实例化以后将InvocationHandler的引用储存在自己的属性中,然后proxyClass每个方法的触发都会触发InvocationHandler的invoke方法,通过反射调用真实对象的的方法。

  • 相关阅读:
    移动页面HTML5自适应手机屏幕宽度
    “流式”前端构建工具——gulp.js 简介
    HDU2602-Bone Collector
    HDU3535-AreYouBusy
    HDU1712-ACboy needs your help
    HDU3496-Watch The Movie
    HDU1171-Big Event in HDU
    POJ2533-Longest Ordered Subsequence
    HDU2084-数塔
    HDU2023-求平均成绩
  • 原文地址:https://www.cnblogs.com/eoss/p/6136526.html
Copyright © 2011-2022 走看看