How the proxy instance pass itself to the InvocationHandler?

我的未来我决定 提交于 2019-12-01 13:31:06

问题


here is the method signature from the Proxy class:

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

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;

Does anyone know?

Thanks


回答1:


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

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.

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.



来源:https://stackoverflow.com/questions/13711944/how-the-proxy-instance-pass-itself-to-the-invocationhandler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!