• Java 源码 Proxy 代理类


    动态代理可以让我们在运行时动态生成代理类,解耦程序。

    源码

    package java.lang.reflect;
    
    /**
     * 创建动态代理对象。
     */
    public class Proxy implements java.io.Serializable {
    
        private static final long serialVersionUID = -2222568056686623797L;
    
        /** parameter types of a proxy class constructor */
        private static final Class<?>[] constructorParams = { InvocationHandler.class };
    
        /**
         * 返回一个代理对象。
         */
        @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) {
                    //Check permissions required to create a Proxy class.
                    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;
                        }
                    });
                }
                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);
            }
        }
    }
    
  • 相关阅读:
    hdu 3791 二叉搜索树
    hdu 4041 Eliminate Witches! 栈和队列
    后缀数组讲解
    Theme Section HDU
    Wow! Such Doge! HDU
    Girls' research HDU
    吉哥系列故事――完美队形II HDU
    Best Reward HDU
    String Problem HDU
    最大最小表示法
  • 原文地址:https://www.cnblogs.com/feiqiangsheng/p/16415976.html
Copyright © 2020-2023  润新知