Java动态代理Proxy.newProxyInstance源码到底干了什么?2021-8-31

Posted 丁丁丁冲鸭丶

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java动态代理Proxy.newProxyInstance源码到底干了什么?2021-8-31相关的知识,希望对你有一定的参考价值。

动态代理

用一个简单的例子来描述动态代理,你想租房子,一般的话,你需要四处找房子,很辛苦,你想在家躺着交了钱就行,所以你找了个代理(中介),代理去找好了房子,和房东商量,你过来看下房子签合同交钱就好了。这就是代理的作用。(找中介需谨慎,中介不同于代码,代码不会骗人)
实际代码中,当你有一个已有的方法,你在不希望修改它的前提下想要扩展它的功能,即可使用动态代理。典型案例就是Spring AOP。

例子代码

/**
 * @author ddd
 * @create 2021-06-25    19:21
 * #desc 动态代理需要一个行为接口
 **/
public interface action {
    public void helloworld();
}

/**
 * @author ddd
 * @create 2021-06-25    
 * #desc 代理类 
 * **/
public class agent implements InvocationHandler {

    private  action action;

    public agent(action action){
        this.action=action;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println(" 辛苦找房! " );
        Object getmethod=method.invoke(action,args);

        return getmethod;
    }
}

/**
 * @author ddd
 * @create 2021-06-25   
 * @desc 顾客
 **/
public class Custom implements action{

    @Override
    public void helloworld() {
        System.out.println(" 看房,签合同,交钱! ");
    }
}

/**
 * @author ddd
 * @create 2021-06-25   
 * @desc 运行类
 **/
public class Main {
    public static void main(String[] args) {
        System.setProperty("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
        action action=new Custom();
        InvocationHandler handlerProxy=new agent(action);
        /*
        这一步会在内存中生成动态代理类
         */
        action actionInstance = (My.DesignPattern.Agent.Jdk.action) Proxy.newProxyInstance(handlerProxy.getClass().getClassLoader(),
                action.getClass().getInterfaces(),
                handlerProxy);
        actionInstance.helloworld();

    }
}

Proxy.newProxyInstance()

大家都说动态代理很重要,用起来也很方便,被代理类实现一个行为接口,代理类实现InvocationHandler 接口,调用Proxy.newProxyInstance()即可生成一个代理类,那到底是怎么生成的代理类?我们进下源码Proxy.newProxyInstance()

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) {
            // check  Proxy  Access 看名字就可以了解,检查是否可以代理
            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;
            if (!Modifier.isPublic(cl.getModifiers())) {
                AccessController.doPrivileged(new PrivilegedAction<Void>() {
                    public Void run() {
                        cons.setAccessible(true);
                        return null;
                    }
                });
            }
            /**
             * 返回new的对象
             */
            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);
        }
    }

getProxyClass0(loader, intfs)

上面有一行代码的注释是查找或者生成一个代理类,我们来这个方法的源码

    private static Class<?> getProxyClass0(ClassLoader loader,
                                           Class<?>... interfaces) {
        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
        // 又封装一层,接着进入proxyClassCache.get
        return proxyClassCache.get(loader, interfaces);
    }

proxyClassCache.get(loader, interfaces)

    public V get(K key, P parameter) {
        Objects.requireNonNull(parameter);

        expungeStaleEntries();
        /**
         * 从缓存中查找,咦,这就是查找一个代理类,但是我们还没有生成过
         * 那在后续肯定有生成代理类放入缓存的操作,
         * 利用缓存的话再次访问的速度就会很快
         *
         * key是什么,handlerProxy.getClass().getClassLoader()
         */
        Object cacheKey = CacheKey.valueOf(key, refQueue);

        // lazily install the 2nd level valuesMap for the particular cacheKey
        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生产者接口,函数型接口,有必要去了解一下
         * 这里用于生产代理类
         */
        Supplier<V> supplier = valuesMap.get(subKey);
        Factory factory = null;

        while (true) {
            if (supplier != null) {
                // supplier might be a Factory or a CacheValue<V> instance
                /**
                 * 非空即可获得代理类
                 * 第一次进入valuesMap是空的,map.get()获取不到
                 * 所以循环条件是while(ture)
                 * 后面会将一个Factory赋值给supplier,然后通过factory.get()来获取
                 */
                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);
            }

            if (supplier == null) {
                supplier = valuesMap.putIfAbsent(subKey, factory);
                if (supplier == null) {
                    // successfully installed Factory
                    /**
                     * 如果为空,就赋值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);
                }
            }
        }
    }

Factory:factory.get()

private final class Factory implements Supplier<V> {

        private final K key;
        private final P parameter;
        private final Object subKey;
        private final ConcurrentMap<Object, Supplier<V>> valuesMap;

        Factory(K key, P parameter, Object subKey,
                ConcurrentMap<Object, Supplier<V>> valuesMap) {
            this.key = key;
            this.parameter = parameter;
            this.subKey = subKey;
            this.valuesMap = valuesMap;
        }

        @Override
        public synchronized V get() { // serialize access
            // re-check
            Supplier<V> supplier = valuesMap.get(subKey);
            if (supplier != this) {
                // something changed while we were waiting:
                // might be that we were replaced by a CacheValue
                // or were removed because of failure ->
                // return null to signal WeakCache.get() to retry
                // the loop
                return null;
            }
            // else still us (supplier == this)

            // create new value
            V value = null;
            try {
                 /**
                 * 关键代码只在这一句,valueFactory.apply(key, parameter)非空即可
                 *  再去看valueFactory.apply(key, parameter)
                 */
                value = Objects.requireNonNull(valueFactory.apply(key, parameter));
            } finally {
                if (value == null) { // remove us on failure
                    valuesMap.remove(subKey, this);
                }
            }
            // the only path to reach here is with non-null value
            assert value != null;

            // wrap value with CacheValue (WeakReference)
            CacheValue<V> cacheValue = new CacheValue<>(value);

            // put into reverseMap
            reverseMap.put(cacheValue, Boolean.TRUE);

            // try replacing us with CacheValue (this should always succeed)
            if (!valuesMap.replace(subKey, this, cacheValue)) {
                throw new AssertionError("Should not reach here");
            }

            // successfully replaced us with new CacheValue -> return the value
            // wrapped by it
            return value;
        }
    }

Proxy:ProxyClassFactory:apply()

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) {
            /**
             * 获取所有接口信息并便利
             */
            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 {
                    /**
                     * Class.forName作用是要求JVM查找并加载指定的类,相当于将接口实例化
                     * ClassLoader loader是我们一开始传入的自己类的加载器
                     */
                    interfaceClass = Class.forName(intf.getName(), false, loader);
                } catch (ClassNotFoundException e) {
                }
                /**
                 * 判断当前类的实例化是否与我们创建的类是同一个加载器生成的
                 */
                if (interfaceClass != intf) {
                    throw new IllegalArgumentException(
                            intf + " is not visible from class loader");
                }
                /*
                 * Verify that the Class object actually represents an
                 * interface.
                 */
                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();
                /**
                 * 如果是public,则放在同一路径下
                 */
                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 + ".";
            }

            /*
             * Choose a name for the proxy class to generate.
             */
            long num = nextUniqueNumber.getAndIncrement();
            String proxyName = proxyPkg + proxyClassNamePrefix + num;

            /*
             * Generate the specified proxy class.
             */
            byte[] proxyClassFile = ProxyGenerator.generateProxyClassjava动态代理是啥

java深入分析Java反射-动态代理 proxy

java-动态代理

Java动态代理实现方式一

Java动态代理

Java动态代理