zoukankan      html  css  js  c++  java
  • JDK动态代理源码学习

    继上一篇博客设计模式之代理模式学习之后http://blog.csdn.net/u014427391/article/details/75115928,本博客介绍JDK动态代理的实现原理,学习一下JDK动态代理的源码。
    Proxy类。该类即为动态代理类,可以使用反编译工具查看jdk里源码。JDK动态代理实现主要由Proxy类的newProxyInstance()方法实现。实现起来很容易,但是学习都要学习原理,所以本博客主要介绍jdk动态代理实现的源码。

    newProxyInstance()方法用于根据传入的接口类型interfaces返回一个动态创建的代理类的实例,方法中第一个参数loader表示代理类的类加载器,第二个参数interfaces表示被代理类实现的接口列表,第三个参数h表示所指派的调用处理程序类。

    首先写个例子实现jdk动态代理
    主题接口类:

    public interface IHello {
        public void sayHello();
    }
    

    被代理的类:

    public class Hello implements IHello{
    
        public void sayHello() {
            System.out.println("hello!");
        }
    }
    

    JDK动态代理InvocationHandler类

    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    
    public class MyInvocationHandler implements InvocationHandler {
        private Object target;//委托类
        public MyInvocationHandler(Object target){
            this.target=target;
        }
    
        @Override
        public Object invoke(Object o, Method method, Object[] args) throws Throwable {
    		/**代理环绕**/
            //执行实际的方法
            Object invoke = method.invoke(target, args);
            return invoke;
        }
    }
    

    写个类模拟字节码文件生成:

    import java.lang.reflect.Proxy;
    
    /**
     * Created by Nicky on 2017/7/20 0020.
     */
    public class Test {
    
        public static void main(String[] args){
            System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
            IHello  ihello = (IHello) Proxy.newProxyInstance(IHello.class.getClassLoader(),  //加载接口的类加载器
                    new Class[]{IHello.class},      //一组接口
                    new MyInvocationHandler(new Hello())); //自定义的InvocationHandler
            ihello.sayHello();
        }
    }
    
    

    实现jdk动态代理是很容易的,不过现在介绍一下jdk源码,理解一下原理实现

    下面看一下Proxy类里的newProxyInstance方法

     @CallerSensitive
        public static Object newProxyInstance(ClassLoader loader,
                                              Class<?>[] interfaces,
                                              InvocationHandler h)
            throws IllegalArgumentException
        {
            Objects.requireNonNull(h);
    		//对象的拷贝
            final Class<?>[] intfs = interfaces.clone();
    		/*
    		 *	权限安全检查
    		 */
            final SecurityManager sm = System.getSecurityManager();
            if (sm != null) {
                checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
            }
    
            /*
             * Look up or generate the designated proxy class.
    		 * (查找或生产指定的代理类。)
             */
            Class<?> cl = getProxyClass0(loader, intfs);
    
            /*
             * Invoke its constructor with the designated invocation handler.
    		 * (使用指定的调用处理程序调用它的构造函数。)
             */
            try {
                if (sm != null) {
                    checkNewProxyPermission(Reflection.getCallerClass(), cl);
                }
    			//获取代理类的构造函数
                final Constructor<?> cons = cl.getConstructor(constructorParams);
                final InvocationHandler ih = h;
    			
    			/*
    			 *	onstructor、Filed、Method都继承自java.lang.reflect.AccessibleObject,
    			 * 	访问非public的方法或者字段都会产生IllegalAccessException异常
    			 */
    			if (!Modifier.isPublic(cl.getModifiers())) {
                    AccessController.doPrivileged(new PrivilegedAction<Void>() {
                        public Void run() {
                            cons.setAccessible(true);//setAccessible()为true可以绕过默认的权限检查
                            return null;
                        }
                    });
                }
    			//根据代理类的构造函数来创建代理对象
                return cons.newInstance(new Object[]{h});
            } catch (IllegalAccessException|InstantiationException e) {
                throw new InternalError(e.toString(), e);
            } catch (InvocationTargetException e) {
                Throwable t = e.getCause();
                if (t instanceof RuntimeException) {
                    throw (RuntimeException) t;
                } else {
                    throw new InternalError(t.toString(), t);
                }
            } catch (NoSuchMethodException e) {
                throw new InternalError(e.toString(), e);
            }
        }
    

    从newProxyInstance方法可以看出,生产代理类是由getProxyClass0获取或者生成的。下面看一下getProxyClass0方法,从方法可以看出如果缓存中有代理类就直接返回代理的副本,否就使用ProxyClassFactory创建代理类。

     /**
         * Generate a proxy class.  Must call the checkProxyAccess method
         * to perform permission checks before calling this.
         */
        private static Class<?> getProxyClass0(ClassLoader loader,
                                               Class<?>... interfaces) {
    		//接口列表数目不能超过65535,因为在class文件中,这些个数都是用4位16进制表示的,所以最大值是2的16次方-1  
    		if (interfaces.length > 65535) {
                throw new IllegalArgumentException("interface limit exceeded");
            }
    		// If the proxy class defined by the given loader implementing
            // the given interfaces exists, this will simply return the cached copy;
            // otherwise, it will create the proxy class via the ProxyClassFactory
            //如果缓存中有代理类就直接返回代理的副本,否就使用ProxyClassFactory创建代理类
            return proxyClassCache.get(loader, interfaces);
        }
    

    proxyClassCache是一个WeakCache类型的缓存,它的构造函数有两个参数,其中一个就是用于生成代理类的ProxyClassFactory,看一下proxyClassCache.get方法的代码:

    public V get(K key, P parameter) {
            Objects.requireNonNull(parameter);
    		//清理持有弱引用的WeakHashMap这种数据结构
            expungeStaleEntries();
    		//从队列中获取cacheKey
            Object cacheKey = CacheKey.valueOf(key, refQueue);
    
            // lazily install the 2nd level valuesMap for the particular cacheKey
            //懒加载的方式封装第二层valueMap,ConcurrentMap是一种线程安全的Map
            ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey);
            if (valuesMap == null) {
                ConcurrentMap<Object, Supplier<V>> oldValuesMap
                    = map.putIfAbsent(cacheKey,
                                      valuesMap = new ConcurrentHashMap<>());
                if (oldValuesMap != null) {
                    valuesMap = oldValuesMap;
                }
            }
    
            // create subKey and retrieve the possible Supplier<V> stored by that
            // subKey from valuesMap
            Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
            Supplier<V> supplier = valuesMap.get(subKey);
            Factory factory = null;
    
            while (true) {
                if (supplier != null) {
                    // supplier might be a Factory or a CacheValue<V> instance
                    //核心代码,从supplier或者value,可能返回工厂实例或者Cache实例,返回实现InvokeHandler的类并包含了所需要的信息。
                    V value = supplier.get();
                    if (value != null) {
                        return value;
                    }
                }
                // else no supplier in cache
                // or a supplier that returned null (could be a cleared CacheValue
                // or a Factory that wasn't successful in installing the CacheValue)
    
                // lazily construct a Factory
                //懒加载方式构建工厂实例
                if (factory == null) {
                    factory = new Factory(key, parameter, subKey, valuesMap);
                }
    			/**填充supplier**/
                if (supplier == null) {
                    supplier = valuesMap.putIfAbsent(subKey, factory);
                    if (supplier == null) {
                        // successfully installed Factory
                        supplier = factory;
                    }
                    // else retry with winning supplier
                } else {
                    if (valuesMap.replace(subKey, supplier, factory)) {
                        // successfully replaced
                        // cleared CacheEntry / unsuccessful Factory
                        // with our Factory
                        supplier = factory;
                    } else {
                        // retry with current supplier
                        supplier = valuesMap.get(subKey);
                    }
                }
            }
        }
    

    若缓存中找不到代理类,就使用ProxyClassFactory生产代理类,看一下ProxyClassFactory类的代码:

     /**
         * A factory function that generates, defines and returns the proxy class given
         * the ClassLoader and array of interfaces.
         */
        private static final class ProxyClassFactory
            implements BiFunction<ClassLoader, Class<?>[], Class<?>>
        {
            // prefix for all proxy class names(统一所以代理类的前缀名都以$Proxy开始)
            private static final String proxyClassNamePrefix = "$Proxy";
    
            // next number to use for generation of unique proxy class names
    		//给每个代理类名加个唯一的编号,如$Proxy0,$Proxy1等等
            private static final AtomicLong nextUniqueNumber = new AtomicLong();
    
            @Override
            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) {
                    }
    				//验证使用classLoad加载的类与传入的类是否相同
                    if (interfaceClass != intf) {
                        throw new IllegalArgumentException(
                            intf + " is not visible from class loader");
                    }
                    /*
                     * Verify that the Class object actually represents an
                     * interface.
    				 * 验证传入的是否为接口类型,因为jdk动态代理只支持接口类型
                     */
                    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.
    			 * 验证传入的接口中有没有非public的接口,若有,就将这些接口全部放在一个包里定义
                 */
                for (Class<?> intf : interfaces) {
                    int flags = intf.getModifiers();
                    if (!Modifier.isPublic(flags)) {
                        accessFlags = Modifier.FINAL;
                        String name = intf.getName();
                        int n = name.lastIndexOf('.');
    					//substring包名
                        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
    				//(如果没有非公共的代理接口,请使用com.sun.proxy包)
                    proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
                }
    
                /*
                 * Choose a name for the proxy class to generate.(为代理类选择一个名称来生成)
                 */
                long num = nextUniqueNumber.getAndIncrement();
    			//生产随机代理类的类名,$Proxy+num
                String proxyName = proxyPkg + proxyClassNamePrefix + num;
    
                /*
                 * Generate the specified proxy class.
    			 * 生产代理类的字节码文件,实现过程看generateProxyClass()方法
                 */
                byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
                    proxyName, interfaces, accessFlags);
                try {
                    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());
                }
            }
        }
    

    从ProxyClassFactory类可以看出生产字节码文件的执行代码由generateProxyClass方法执行:

    public static byte[] generateProxyClass(final String var0, Class<?>[] var1, int var2) {
    		//新建ProxyGenerator实例,放入参数proxyName, interfaces, accessFlags,也即代理名称,接口列表,是否允许代理的flag标志
            ProxyGenerator var3 = new ProxyGenerator(var0, var1, var2);
            //真正实现生产字节码文件的方法
            final byte[] var4 = var3.generateClassFile();
            //检查是否允许生产文件,如果可以就保存class文件到本地
            if(saveGeneratedFiles) {
                AccessController.doPrivileged(new PrivilegedAction() {
                    public Void run() {
                        try {
                            int var1 = var0.lastIndexOf(46);
                            Path var2;
                            if(var1 > 0) {
                                Path var3 = Paths.get(var0.substring(0, var1).replace('.', File.separatorChar), new String[0]);
                                Files.createDirectories(var3, new FileAttribute[0]);
                                var2 = var3.resolve(var0.substring(var1 + 1, var0.length()) + ".class");
                            } else {
                                var2 = Paths.get(var0 + ".class", new String[0]);
                            }
    
                            Files.write(var2, var4, new OpenOption[0]);
                            return null;
                        } catch (IOException var4x) {
                            throw new InternalError("I/O exception saving generated file: " + var4x);
                        }
                    }
                });
            }
    
            return var4;
        }
    

    看了这么久,终于知道generateClassFile是真正执行class文件生成的方法,现在看一下generateClassFile的代码:

    private byte[] generateClassFile() {
    		/**将Object类的三个方法hashCode、equals、toString都加到代理方法里,生产class文件时一起重写**/
            this.addProxyMethod(hashCodeMethod, Object.class);
            this.addProxyMethod(equalsMethod, Object.class);
            this.addProxyMethod(toStringMethod, Object.class);
            Class[] var1 = this.interfaces;
            int var2 = var1.length;
    
            int var3;
            Class var4;
            //将接口和接口下的方法对应起来
            for(var3 = 0; var3 < var2; ++var3) {
                var4 = var1[var3];
                Method[] var5 = var4.getMethods();
                int var6 = var5.length;
    
                for(int var7 = 0; var7 < var6; ++var7) {
                    Method var8 = var5[var7];
                    this.addProxyMethod(var8, var4);
                }
            }
    	
            Iterator var11 = this.proxyMethods.values().iterator();
    
            List var12;
            //检查所有代理方法的返回类型
            while(var11.hasNext()) {
                var12 = (List)var11.next();
                checkReturnTypes(var12);
            }
    
            Iterator var15;
            try {
            //将构造函数放在方法里,这个构造方法只有一个,即一个带有InvocationHandler实例的构造方法
                this.methods.add(this.generateConstructor());
                var11 = this.proxyMethods.values().iterator();
    			//遍历代理方法
                while(var11.hasNext()) {
                    var12 = (List)var11.next();
                    var15 = var12.iterator();
    
                    while(var15.hasNext()) {
                        ProxyGenerator.ProxyMethod var16 = (ProxyGenerator.ProxyMethod)var15.next();
                        //给每一个代理方法加一个Method类型的属性,数字10是class文件的标识符,代表这些属性都是private static的
                        this.fields.add(new ProxyGenerator.FieldInfo(var16.methodFieldName, "Ljava/lang/reflect/Method;", 10));
                        //将方法都加到代理类的方法里
                        this.methods.add(var16.generateMethod());
                    }
                }
    			//加入一个静态的类构造方法,将每一个属性初始化
                this.methods.add(this.generateStaticInitializer());
            } catch (IOException var10) {
                throw new InternalError("unexpected I/O Exception", var10);
            }
    		//方法和属性个数都不能超过65535,因为在class文件中,这些个数都是用4位16进制表示的,所以最大值是2的16次方-1  
            if(this.methods.size() > 'uffff') {
                throw new IllegalArgumentException("method limit exceeded");
            } else if(this.fields.size() > 'uffff') {
                throw new IllegalArgumentException("field limit exceeded");
            } else {
    	        //将类名中的.转成成斜线为了写入class文件。  
                this.cp.getClass(dotToSlash(this.className));
                this.cp.getClass("java/lang/reflect/Proxy");
                var1 = this.interfaces;
                var2 = var1.length;
    
                for(var3 = 0; var3 < var2; ++var3) {
                    var4 = var1[var3];
                    this.cp.getClass(dotToSlash(var4.getName()));
                }
    
                this.cp.setReadOnly();
                //开始真正的写class文件
                ByteArrayOutputStream var13 = new ByteArrayOutputStream();
                DataOutputStream var14 = new DataOutputStream(var13);
    
                try {
    	            //写入class文件的标识号,标识这是一个class文件  
                    var14.writeInt(-889275714);
                    //次版本号0
                    var14.writeShort(0);
                    //主版本号,49代表的是JDK1.5
                    var14.writeShort(49);
                    this.cp.write(var14);
                    var14.writeShort(this.accessFlags);
                    //写入代理类的类名
                    var14.writeShort(this.cp.getClass(dotToSlash(this.className)));
                    var14.writeShort(this.cp.getClass("java/lang/reflect/Proxy"));
                    //写入代理类所实现的接口数量  
                    var14.writeShort(this.interfaces.length);
                    Class[] var17 = this.interfaces;
                    int var18 = var17.length;
    
                    for(int var19 = 0; var19 < var18; ++var19) {
                        Class var22 = var17[var19];
                        var14.writeShort(this.cp.getClass(dotToSlash(var22.getName())));
                    }
    				//写入属性个数
                    var14.writeShort(this.fields.size());
                    var15 = this.fields.iterator();
    				//写入属性描述
                    while(var15.hasNext()) {
                        ProxyGenerator.FieldInfo var20 = (ProxyGenerator.FieldInfo)var15.next();
                        var20.write(var14);
                    }
    				//写入方法个数
                    var14.writeShort(this.methods.size());
                    var15 = this.methods.iterator();
    				//写入方法描述,方法的code属性,以及构造方法和类构造方法
                    while(var15.hasNext()) {
                        ProxyGenerator.MethodInfo var21 = (ProxyGenerator.MethodInfo)var15.next();
                        var21.write(var14);
                    }
    
                    var14.writeShort(0);
                    return var13.toByteArray();
                } catch (IOException var9) {
                    throw new InternalError("unexpected I/O Exception", var9);
                }
            }
        }
    

    使用反编译工具查看生产的字节码文件代码,说明了下文件中生成的部分与刚才分析的时候写入的过程的对应关系。:

    package com.sun.proxy;
    
    import IHello;
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    import java.lang.reflect.UndeclaredThrowableException;
    
    //生产的代理类都是以$Proxy+唯一的数字为类名的,继承Proxy类同时implements你主题接口
    public final class $Proxy0 extends Proxy
      implements IHello
    {
      private static Method m1;
      private static Method m3;
      private static Method m2;
      private static Method m0;
    
    //将InvocationHandler实例放在构造方法里
      public $Proxy0(InvocationHandler paramInvocationHandler)
        throws 
      {
        super(paramInvocationHandler);
      }
    
    //重写Object的equals方法
      public final boolean equals(Object paramObject)
        throws 
      {
        try
        {
          return ((Boolean)this.h.invoke(this, m1, new Object[] { paramObject })).booleanValue();
        }
        catch (RuntimeException localRuntimeException)
        {
          throw localRuntimeException;
        }
        catch (Throwable localThrowable)
        {
        }
        throw new UndeclaredThrowableException(localThrowable);
      }
    
    
      public final void sayHello()
        throws 
      {
        try
        {
          this.h.invoke(this, m3, null);
          return;
        }
        catch (RuntimeException localRuntimeException)
        {
          throw localRuntimeException;
        }
        catch (Throwable localThrowable)
        {
        }
        throw new UndeclaredThrowableException(localThrowable);
      }
    
      public final String toString()
        throws 
      {
        try
        {
          return (String)this.h.invoke(this, m2, null);
        }
        catch (RuntimeException localRuntimeException)
        {
          throw localRuntimeException;
        }
        catch (Throwable localThrowable)
        {
        }
        throw new UndeclaredThrowableException(localThrowable);
      }
    
      public final int hashCode()
        throws 
      {
        try
        {
          return ((Integer)this.h.invoke(this, m0, null)).intValue();
        }
        catch (RuntimeException localRuntimeException)
        {
          throw localRuntimeException;
        }
        catch (Throwable localThrowable)
        {
        }
        throw new UndeclaredThrowableException(localThrowable);
      }
    
      static
      {
        try
        {
        //每一个属性所代表的Method都是与上面加入代理方法列表时与固定类绑定的,这是class文件中的格式,方法要与固定的类绑定 
          m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] { Class.forName("java.lang.Object") });
          m3 = Class.forName("IHello").getMethod("sayHello", new Class[0]);
          m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
          m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
          return;
        }
        catch (NoSuchMethodException localNoSuchMethodException)
        {
          throw new NoSuchMethodError(localNoSuchMethodException.getMessage());
        }
        catch (ClassNotFoundException localClassNotFoundException)
        {
        }
        throw new NoClassDefFoundError(localClassNotFoundException.getMessage());
      }
    }
    
  • 相关阅读:
    js-url打开方式
    eclipse删除所有空行
    Oracle重启 error: ora-01034:oracle not available ora-27101:shared memory realm does not exist
    最近面试遇到了高阶函数的概念混乱了
    关于跨域的cookie问题
    二叉树 呜呜
    函数的尾递归
    react context
    二叉树
    dom3级事件
  • 原文地址:https://www.cnblogs.com/mzq123/p/7215966.html
Copyright © 2011-2022 走看看