Java动态代理解析

动态代理原理解析

一. 代理模式例子:

  1. 目标类及代理类统一接口
/**
 * 用户操作接口
 * Created by Deity on 2017/11/12.
 */

public interface IUserService {
    /**查询所有用户*/
    void queryAllUser();
}
  1. 目标实现类
/**
 * 用户接口实现类
 * Created by Deity on 2017/11/12.
 */

public class UserServiceImpl implements IUserService {
    /**
     * 查询所有用户
     */
    @Override
    public void queryAllUser() {
        System.out.println("查询所有的用户");
    }
}
  1. 自定义的代理模式处理程序
/**
 * 自定义的代理模式处理程序
 * Created by Deity on 2017/11/12.
 */

public class UserServiceInvocationHandler implements InvocationHandler{
    /**需要被代理的目标对象*/
    private Object object;

    public UserServiceInvocationHandler(Object object){
        super();
        this.object = object;
    }

    /**
     * Processes a method invocation on a proxy instance and returns
     * the result.  This method will be invoked on an invocation handler
     * when a method is invoked on a proxy instance that it is
     * associated with.
     *
     * @param proxy  the proxy instance that the method was invoked on
     * @param method the {@code Method} instance corresponding to
     *               the interface method invoked on the proxy instance.  The declaring
     *               class of the {@code Method} object will be the interface that
     *               the method was declared in, which may be a superinterface of the
     *               proxy interface that the proxy class inherits the method through.
     * @param args   an array of objects containing the values of the
     *               arguments passed in the method invocation on the proxy instance,
     *               or {@code null} if interface method takes no arguments.
     *               Arguments of primitive types are wrapped in instances of the
     *               appropriate primitive wrapper class, such as
     *               {@code java.lang.Integer} or {@code java.lang.Boolean}.
     * @return the value to return from the method invocation on the
     * proxy instance.  If the declared return type of the interface
     * method is a primitive type, then the value returned by
     * this method must be an instance of the corresponding primitive
     * wrapper class; otherwise, it must be a type assignable to the
     * declared return type.  If the value returned by this method is
     * {@code null} and the interface method's return type is
     * primitive, then a {@code NullPointerException} will be
     * thrown by the method invocation on the proxy instance.  If the
     * value returned by this method is otherwise not compatible with
     * the interface method's declared return type as described above,
     * a {@code ClassCastException} will be thrown by the method
     * invocation on the proxy instance.
     * @throws Throwable the exception to throw from the method
     *                   invocation on the proxy instance.  The exception's type must be
     *                   assignable either to any of the exception types declared in the
     *                   {@code throws} clause of the interface method or to the
     *                   unchecked exception types {@code java.lang.RuntimeException}
     *                   or {@code java.lang.Error}.  If a checked exception is
     *                   thrown by this method that is not assignable to any of the
     *                   exception types declared in the {@code throws} clause of
     *                   the interface method, then an
     *                   {@link UndeclaredThrowableException} containing the
     *                   exception that was thrown by this method will be thrown by the
     *                   method invocation on the proxy instance.
     * @see UndeclaredThrowableException
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("before method invoke");
        Object result = method.invoke(object,args);
        System.out.println("after method invoke");
        return result;
    }

    /**获取目标对象的代理对象*/
    public Object obtainProxyInstance(){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),object.getClass().getInterfaces(),this);
    }
}

4.代理模式用例测试

/**
 * 代理模式用例测试
 */
public class ExampleUnitTest {
    @Test
    public void testPoxy() throws Exception {
        IUserService userService = new UserServiceImpl();
        UserServiceInvocationHandler userServiceInvocationHandler = new UserServiceInvocationHandler(userService);
        IUserService proxyUserService = (IUserService) userServiceInvocationHandler.obtainProxyInstance();
        proxyUserService.queryAllUser();
    }
}
  1. 运行结果:


    运行结果

二.动态代理中底层为我们做了什么
可以发现,在此过程中,我们实现了一个自定义的代理模式调用处理程序,并重写的了这个接口中的invoke()方法.这个invoke()方法在什么情况下会执行呢?

invoke()方法是proxy实例 处理方法调用并返回结果的入口,当一个proxy实例调用方法时,与之关联的InvocationHandler 的invoke()方法就会执行.
拿我们上面的例子来说,proxyUserService调用了queryAllUser()方法会触发UserServiceInvocationHandler 执行 invoke() 方法。

我们发现这个方法中存在3个参数

proxy 该方法被调用的代理实例,就是上面例子中的proxyUserService实例.
method 对应于在代理实例上调用的接口方法,Method对象的声明类将是方法声明的接口,它可能是代理类继承方法的代理接口的超级接口。
args 代理实例中方法调用的入参(也有可能是空值)
关于返回值: 如果接口方法的声明返回类型是基本类型,则此方法返回的值必须是相应基本包装类的实例,否则,它必须是可分配给声明的返回类型的类型(有点绕口),如果此方法返回的值为null,并且接口方法的返回类型为原始类型,则代理实例上的方法调用将抛出NullPointerException异常。 如果此方法返回的值与上述的接口方法的声明返回类型不兼容,则代理实例上的方法调用将抛出ClassCastException。

上面我们说了:当一个proxy实例调用方法时,与之关联的InvocationHandler 的invoke()方法就会执行,那么这个proxy实例是怎么来的呢?

三.生成proxy实例
跟着我看下这个生成Proxy实例的方法签名:

/**
*返回指定接口的动态构建类的实例,返回的proxy实例的方法调用,
接口必须对类加载器可见(public修饰符,protect修饰符),并且不允许重
复,非public修饰的接口必须在同一个包下定义
*/
public static Object newProxyInstance (ClassLoader loader, Class[]<?> 
interfaces, InvocationHandler invocationHandler)

看下这个方法的源码实现

public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)
throws IllegalArgumentException{
        //如果没有定义调度处理程序,直接抛出空指针异常
        if (h == null) {
            throw new NullPointerException();
        }
        //查找或者生成指定的代理类
        Class<?> cl = getProxyClass0(loader, interfaces);
        //使用指定的调度处理程序调用其构造函数
        try {
        //其中constructorParams是代理类构造函数的参数类型(一个常量)
            final Constructor<?> cons=cl.getConstructor(constructorParams);
            return newInstance(cons, h);
        } catch (NoSuchMethodException e) {
            throw new InternalError(e.toString());
        }
    }

我们发现我们自定义的调度处理程序以入参的形式传递到生成代理实例的构造函数中,这也间接解释了为什么proxy实例的方法被调用会触发InvocationHandler 的invoke()方法执行的一个原因.

newProxyInstance()方法给我们引出了3个疑点。

  1. getProxyClass0(loader, interfaces)
  2. cl.getConstructor(constructorParams)
  3. newInstance(cons, h)

以上三个方法又做了什么

/**生成一个代理类,在调用此方法之前,需要调用checkProxyAccess方法执行权限检测 */
private static Class<?> getProxyClass0(ClassLoader loader,
                                           Class<?>... interfaces)

来看下这个方法的源码(非官方源码,非关键内容已删减)

    private static Class<?> getProxyClass0(ClassLoader loader,
                                           Class<?>... interfaces) {
        //接口数量限制,一般不会出现这种情况.
        if (interfaces.length > 65535) {
            throw new IllegalArgumentException("interface limit exceeded");
        }
        Class<?> proxyClass = null;
        //收集接口名称以用作代理类缓存的关键字 
        String[] interfaceNames = new String[interfaces.length];

        //用于检测重复
        Set<Class<?>> interfaceSet = new HashSet<>();
        for (int i = 0; i < interfaces.length; i++) {
            /*
             * 验证类加载器是否将此接口的名称解析为同一个Class对象。
             * 或者说这个接口对类加载器是否可见
             */
            ....
            //验证Class对象是否是一个接口。
            ....
            //确认这个接口不重复
            ....
            //存储Key值
            interfaceNames[i] = interfaceName;
        }

        /*
         * Using string representations of the proxy interfaces as
         * keys in the proxy class cache (instead of their Class
         * objects) is sufficient because we require the proxy
         * interfaces to be resolvable by name through the supplied
         * class loader, and it has the advantage that using a string
         * representation of a class makes for an implicit weak
         * reference to the class.
         */
        List<String> key = Arrays.asList(interfaceNames);

        //为类加载器查找或创建代理类缓存
        //这个映射将在这个方法的持续时间内保持有效,而不需要进一步的
       //同步,因为只有当类加载器变得不可达时,映射才会被移除。
        Map<List<String>, Object> cache;
        synchronized (loaderToCache) {
            cache = loaderToCache.get(loader);
            if (cache == null) {
                cache = new HashMap<>();
                loaderToCache.put(loader, cache);
            }
        }

        /*
         * 使用Key值查找代理类缓存接口类表,这种查找可能会有三种情况
         * 1.当前的类加载器没有实现了接口列表的代理类.返回空值
         * 2.如果当前正在生成接口列表的代理类,返回
         * pendingGenerationMarker对象
         * 3.如果已经生成了接口列表的代理类,返回代理类对象的弱引用
         */
        synchronized (cache) {
            /*
             * Note that we need not worry about reaping the cache for
             * entries with cleared weak references because if a proxy class
             * has been garbage collected, its class loader will have been
             * garbage collected as well, so the entire cache will be reaped
             * from the loaderToCache map.
             */
            do {
                Object value = cache.get(key);
                if (value instanceof Reference) {
                    proxyClass = (Class<?>) ((Reference) value).get();
                }
                if (proxyClass != null) {
                    // proxy class already generated: return it
                    return proxyClass;
                } else if (value == pendingGenerationMarker) {
                    // proxy class being generated: wait for it
                    try {
                        cache.wait();
                    } catch (InterruptedException e) {
                        /*
                         * The class generation that we are waiting for should
                         * take a small, bounded time, so we can safely ignore
                         * thread interrupts here.
                         */
                    }
                    continue;
                } else {
                    /*
                     * No proxy class for this list of interfaces has been
                     * generated or is being generated, so we will go and
                     * generate it now.  Mark it as pending generation.
                     */
                    cache.put(key, pendingGenerationMarker);
                    break;
                }
            } while (true);
        }

        try {
            String proxyPkg = null;     // package to define proxy class in

            /*
             * 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 (int i = 0; i < interfaces.length; i++) {
                int flags = interfaces[i].getModifiers();
                if (!Modifier.isPublic(flags)) {
                    String name = interfaces[i].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 the default package.
                proxyPkg = "";
            }

            {
                // Android-changed: Generate the proxy directly instead of calling
                // through to ProxyGenerator.
                List<Method> methods = getMethods(interfaces);
                Collections.sort(methods, ORDER_BY_SIGNATURE_AND_SUBTYPE);
                validateReturnTypes(methods);
                List<Class<?>[]> exceptions = deduplicateAndGetExceptions(methods);

                Method[] methodsArray = methods.toArray(new Method[methods.size()]);
                Class<?>[][] exceptionsArray = exceptions.toArray(new Class<?>[exceptions.size()][]);

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

                proxyClass = generateProxy(proxyName, interfaces, loader, methodsArray,
                        exceptionsArray);
            }
            // add to set of all generated proxy classes, for isProxyClass
            proxyClasses.put(proxyClass, null);

        } finally {
            /*
             * We must clean up the "pending generation" state of the proxy
             * class cache entry somehow.  If a proxy class was successfully
             * generated, store it in the cache (with a weak reference);
             * otherwise, remove the reserved entry.  In all cases, notify
             * all waiters on reserved entries in this cache.
             */
            synchronized (cache) {
                if (proxyClass != null) {
                    cache.put(key, new WeakReference<Class<?>>(proxyClass));
                } else {
                    cache.remove(key);
                }
                cache.notifyAll();
            }
        }
        return proxyClass;
    }

扩展阅读:
来自IBM的 Java 动态代理机制分析及扩展,第 1 部分

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,937评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,503评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,712评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,668评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,677评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,601评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,975评论 3 396
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,637评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,881评论 1 298
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,621评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,710评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,387评论 4 319
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,971评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,947评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,189评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,805评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,449评论 2 342

推荐阅读更多精彩内容