Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does the method invoke() in InvocationHandler have an parameter Object proxy?

When you r checking out that the method invoke(Object proxy, Method method, Object[] args) declaration & the doc statement,you will find that the input parameter proxy

proxy - the proxy instance that the method was invoked on

when I am doing a test on java dynamic proxy,I find this proxy is produced by vm.So I do want to know why the method invoke has this param,which is surely nothing except that is just an object ($proxy0 )but don't have the actual action for our usage?

like image 875
Eric Chen Avatar asked Dec 20 '10 12:12

Eric Chen


People also ask

What is the object that invokes the method?

Parameters. obj − the object the underlying method is invoked from. args − the arguments used for the method call.

What is a proxy object in Java?

Proxy is a structural design pattern that provides an object that acts as a substitute for a real service object used by a client. A proxy receives client requests, does some work (access control, caching, etc.) and then passes the request to a service object.

What is a dynamic proxy invocation handler?

A dynamic proxy can be thought of as a kind of Facade, but one that can pretend to be an implementation of any interface. Under the cover, it routes all method invocations to a single handler – the invoke() method.

What is proxy in subclass?

A proxy class is present in java. lang package. A proxy class has certain methods which are used for creating dynamic proxy classes and instances, and all the classes created by those methods act as subclasses for this proxy class. Class declaration: public class Proxy extends Object implements Serializable.


2 Answers

This very useful if you have single invocation handle for multiple proxy objects. So you can use hash map to store proxy states information. For example - Mokito test framework store proxy invocation history.

like image 120
Alex Avatar answered Oct 05 '22 10:10

Alex


if you are chinese ,you can read this article http://rejoy.iteye.com/blog/1627405

he makes a decompliation of $proxy0.class, you should know that $proxy0 extends Proxy

public final class $Proxy0 extends Proxy  
    implements UserService 

and there is a function in $proxy0:

public final void add()  
    {  
        try  
        {  
            //the h(invocationhandler) is in Proxy class,so we need pass this $proxy0 instance to super ,so the super(Proxy) can invoke($proxy0,method,args)
            super.h.invoke(this, m3, null);  
            return;  
        }  
        catch(Error _ex) { }  
        catch(Throwable throwable)  
        {  
            throw new UndeclaredThrowableException(throwable);  
        }  
    }  
like image 23
Joey Avatar answered Oct 05 '22 10:10

Joey