代理实例如何将自身传递给InvocationHandler? [英] How the proxy instance pass itself to the InvocationHandler?

查看:99
本文介绍了代理实例如何将自身传递给InvocationHandler?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是Proxy类的方法签名:

here is the method signature from the Proxy class:

Object java.lang.reflect.Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException

我检查源代码代理类中的newProxyInstance,我无法找到代理对象将自身传递给InvocationHandler方法的位置

I check the source code of the newProxyInstance in the Proxy Class, i couldn't find where the proxy object pass itself to the InvocationHandler method

public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable;

有谁知道吗?

谢谢

推荐答案

您可以通过常规方式提供参考。一种常见的模式是创建一个最终变量来引用目标,并将 InvocationTargetHandler 的匿名实现传递给 Proxy.newProxyInstance 方法如下:

You're on the hook to provide the reference through the usual means. One common pattern is to create a final variable to reference the target and pass an anonymous implementation of InvocationTargetHandler to the Proxy.newProxyInstance method like so:

final Object myObject = /*initialize the proxy target*/;
final Object proxy = Proxy.newProxyInstance(
    classLoader,
    new Class[] { /*your interface(s)*/ }, 
    new InvocationTargetHandler() {
        public Object invoke(Object proxy, Method method, Object[] args) {
            return method.invoke(myObject, args);
        }
});

这个例子是世界上最无意义的代理,因为它可以在不做任何事情的情况下修补所有方法调用,但你可以用各种有趣的东西填写 InvocationTargetHandler

This example is the most pointless proxy in the world because it patches all method calls through without doing anything, but you can fill in the InvocationTargetHandler with all sorts of fun stuff.

有时候API感觉有点笨拙因为代理对象不构成合同的一部分,但JDK作者希望提供代理类存在的可能性,而无需支持具体实现。他们这样做是非常有用的......单元测试中的模拟对象就是一个很好的例子。

Sometimes the API feels a little bit klunky because the proxied object doesn't form part of the contract, but the JDK authors wanted to provide the possibility for the proxy class to exist without a backing concrete implementation. It's quite useful that they did it that way...mock objects in your unit tests are a great of example.

这篇关于代理实例如何将自身传递给InvocationHandler?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆