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

本文介绍了Java动态代理的概念,通过租房中介的例子解释其作用,并展示了动态代理的代码实现。文中详细解析了`Proxy.newProxyInstance()`方法的工作流程,包括`getProxyClass0()`和`proxyClassCache.get()`等关键步骤。文章还探讨了生成的代理类及其`helloworld()`方法的实现,并总结了动态代理的特性与优势。
摘要由CSDN通过智能技术生成

动态代理

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

生成的代理类

以上过程就生成了代理类,那最终我们生成的代理类在哪呢?
在开头的例子中,我们在Main类中加了这么一行代码,它可以将我们生成的代理类保存到本地

System.setProperty("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");

运行之后就可以看到
在这里插入图片描述

代理类的helloworld()

我们来看代理类的helloworld方法

public final class $Proxy0 extends Proxy implements action{
	---
	/*
	而我们一开始在最初的main方法中,
	 InvocationHandler handlerProxy=new agent(action);
     action actionInstance = (My.DesignPattern.Agent.Jdk.action)Proxy.newProxyInstance(handlerProxy.getClass().getClassLoader(),
                action.getClass().getInterfaces(),
                handlerProxy);
	又通过$Proxy0构造方法传了new agent(action),是InvocationHandler 的实现类
	所以Proxy 类中的InvocationHandl就是我们写的代理类
	*/
	public $Proxy0(InvocationHandler var1) throws  {
        super(var1);
    }
public final void helloworld() throws  {
        try {
         /**
         * 调用了父类的h变量的invoke,即agent类中的invoke
         */
            super.h.invoke(this, m3, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }
    ---
    }

总结

1、动态代理基于反射,可以在程序运行时得到一个类的全部信息。
2、反射基于JVM的类加载机制和JVM内存模型中类,接口模板的存放。
3、动态代理通过以上技术在运行时动态生成一个代理对象。
4、为什么说是动态,因为agent传入的参数是action接口,可以在运行时传入任何实现了action接口的类来完成代理,使用更加灵活。
5、此文仅个人理解,并且因为反射涉及JVM知识,内容过多,未进一步深入。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值