首页 > 其他分享 >JDK动态代理学习笔记

JDK动态代理学习笔记

时间:2022-11-03 12:23:36浏览次数:50  
标签:JDK valuesMap 代理 笔记 Class supplier new null throw

JDK动态代理学习

2022.10.23

今天在看Java基础的时候,看到Reflect方面,资料提到各种框架离不开Reflect,同时动态代理也依赖于Reflect

去随便搜了点动态代理的文章,看了看如何调用API,感兴趣之后啃了点源码,同时了解了函数式接口的广泛用处,非常的有收获

使用

先看看如何使用

  • 首先要有自己定义的委托类RealSubject,同时这个类必须有一个实现的接口,称为Subject
    • 至于为什么要有一个接口,因为最终生成的代理类需要实现这个接口,生成的代理类对象用户需要用一个Subject引用来接收
  • 其次要自定义InvocationHandler的实现类InvocationHandlerImpl,这个实现类需要依赖一个RealSubject对象,重写invoke方法,在用method对象调用invoke()

最终使用

源码

因为最终代理对象是通过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对象
        Class<?> cl = getProxyClass0(loader, intfs);

        /*
         * Invoke its constructor with the designated invocation handler.
         */
        try {
            if (sm != null) {
                checkNewProxyPermission(Reflection.getCallerClass(), cl);
            }
			
			//得到代理对象类的构造器对象(这个构造器的参数是InvocationHandler对象)
			//constructParams是一个数组,只有InvocationHandler.class
            final Constructor<?> cons = cl.getConstructor(constructorParams);
            final InvocationHandler ih = h;
            
            //如果构造器不是公有的,则设置为public
            if (!Modifier.isPublic(cl.getModifiers())) {
                AccessController.doPrivileged(new PrivilegedAction<Void>() {
                    public Void run() {
                        cons.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);
        }
    }

这里还看不出什么东西,所以继续追传入的参数,也就是loader和interfaces的clone

进入getProxyClass0看看

发现是调用了缓存对象的方法,交给缓存对象去处理了,继续追踪

发现这里是把loader作为key值,interfaces作为parameter

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

    	//清除过期entity
        expungeStaleEntries();

        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<V> supplier = valuesMap.get(subKey);
        Factory factory = null;

    	//这一个while循环需要配合Factory(Proxy的内部类)来看,Factory构造的时候把valueMap的引用作为参数一起传进去了,同时这个循环考虑到了多线程
        while (true) {
            if (supplier != null) {
                // supplier might be a Factory or a CacheValue<V> instance
                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
                    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类内部看看,需要看看怎么封装被缓存的数据的

   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 {
                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;
        }
    }

这里是关键,拿到subKeyFactory.apply(key, parameter)得到的value,包装成CacheValue就注入到缓存中了,也就是这个subKeyFactory.apply(key, parameter)是关键

继续追踪,需要看subKeyFactory是什么变量

是一个接口引用,那么就从这个WeakCache被构造的时候传入的构造器参数来看吧

这里可以看到,这个valueFactory指向的是一个ProxyClassFactory对象

查看这个类的apply方法,有点长,不过前面很多是在做一些错误检查,直接跳到最后看即可

 @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) {
                }
                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();
                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());
            }
        }
    }

这里是最终的一部了,上面在拼接类名,下面直接用得到的内容生成了一个代理类的字节数组

可以用流对象把这个字节数组反序列化一下

最终得到的.class文件中的代码

可以很明显的看到,调用sayHello()方法时,其实是调用了父类(Proxy)的h对象(我们注入的InvocationHandlerImpl对象)的invoke方法,这样一切就清楚了

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

import com.he.dynamicProxyDemo.Subject;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;

public final class ProxySubject extends Proxy implements Subject {
    private static Method m1;
    private static Method m3;
    private static Method m2;
    private static Method m4;
    private static Method m0;

    public ProxySubject(InvocationHandler var1) throws  {
        super(var1);
    }

    public final boolean equals(Object var1) throws  {
        try {
            return (Boolean)super.h.invoke(this, m1, new Object[]{var1});
        } catch (RuntimeException | Error var3) {
            throw var3;
        } catch (Throwable var4) {
            throw new UndeclaredThrowableException(var4);
        }
    }

    public final String sayHello(String var1) throws  {
        try {
            return (String)super.h.invoke(this, m3, new Object[]{var1});
        } catch (RuntimeException | Error var3) {
            throw var3;
        } catch (Throwable var4) {
            throw new UndeclaredThrowableException(var4);
        }
    }

    public final String toString() throws  {
        try {
            return (String)super.h.invoke(this, m2, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    public final String sayGoodbye() throws  {
        try {
            return (String)super.h.invoke(this, m4, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    public final int hashCode() throws  {
        try {
            return (Integer)super.h.invoke(this, m0, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    static {
        try {
            m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
            m3 = Class.forName("com.he.dynamicProxyDemo.Subject").getMethod("sayHello", Class.forName("java.lang.String"));
            m2 = Class.forName("java.lang.Object").getMethod("toString");
            m4 = Class.forName("com.he.dynamicProxyDemo.Subject").getMethod("sayGoodbye");
            m0 = Class.forName("java.lang.Object").getMethod("hashCode");
        } catch (NoSuchMethodException var2) {
            throw new NoSuchMethodError(var2.getMessage());
        } catch (ClassNotFoundException var3) {
            throw new NoClassDefFoundError(var3.getMessage());
        }
    }
}

标签:JDK,valuesMap,代理,笔记,Class,supplier,new,null,throw
From: https://www.cnblogs.com/mumayiren/p/16854027.html

相关文章

  • 配置Squid代理服务器
    添加双网卡vm1是内网同学vm2是外网通信Squid服务器生成外网网卡配置文件外网网卡设置IP地址然后重启服务查看网卡生效了没修改配置文件开启路由功能更新内核参数开启路由转......
  • 软件技术基础学习笔记(2)——实习一个命令行统计数统计创程序
    软件技术基础浙江理工大学软件技术基础作业目标实习一个命令行统计数统计创程序姓名学号周彬豪20203330300093软件技术基础学习笔记(2)——实习一个命令......
  • ASEMI代理LSIC2SD120A05-力特Sic肖特基二极管
    编辑:llASEMI代理LSIC2SD120A05-力特Sic肖特基二极管型号:LSIC2SD120A05品牌:LITTELFUSE/力特封装:TO-220-2L特性:Sic肖特基二极管正向电流:5A反向耐压:1200V恢复时间:35ns......
  • 为什么HTTP代理会出现“返回403 forbidden”
    平时我们在使用HTTP代理的过程中,稍有不慎就会出现各种各样的错误代码,其中“403forbidden”就是常见的一种。它属于HTTP协议中的一个状态码(StatusCode),可以简单的理......
  • ECharts学习笔记
    目录ECharts学习笔记原文链接ECharts配置语法第一步:创建HTML页面第二步:为ECharts准备一个具备高宽的DOM容器第三步:设置配置信息图形示例饼图柱状图下钻柱状图E......
  • HTTP代理究竟是宜没好货还是一分价钱一分货
    我们在HTTP代理选择的时候,不少朋友都会犯难,到底是便宜没好货,一分价钱一分货?还是只买对的,其实代理不一定要买多便宜,也不一定要买多昂贵的。还是之前我们老生常谈......
  • 免费的HTTP代理有什么好处吗
    我们在接手爬虫业务时候,往往需要选择一款适合自己业务的HTTP代理,通常都会选择所谓性价比高的代理,可是真的是性价比越高就越适合我们的业务吗?其实不然。不少朋友,尤......
  • cloud stream 官方文档阅读笔记3
    核心概念4.1应用模型一个springcloudStream应用包括了一个消息中间件作为核心。某个应用通过springcloudStream使用input和output通道与外界(注:消息队列)进行消息交......
  • 设计模式之代理,手动实现动态代理,揭秘原理实现
    开心一刻周末,带着老婆儿子一起逛公园。儿子一个人跑在前面,吧唧一下不小心摔了一跤,脑袋瓜子摔了个包,稀里哗啦的哭道:“爸爸,我会不会摔成傻子!”我指了指我头上的伤痕安......
  • (笔记)ROS2 colcon build报错:ModuleNotFoundError: No module named ‘catkin_pkg‘
     在使用ROS2时,使用colconbuild编译时,报错如下:1Starting>>>fishbot_navigation22---stderr:fishbot_navigation23Traceback(mo......