Transferred from this public number:
I'll talk about Invocationhandler today. Speaking of Invocationhandler have to mention is the proxy mode, what is the proxy mode, for example, you play games, pay a leveling, leveling is actually logged in your account, pretending that you help you upgrade to play strange. Another example of buying a house, you need to entrust intermediary to help you to deal with some things, intermediary in handling these things, the actual use of your identity card, identity information to handle.
Proxy mode is the same, for example, there is a class, one method is to compress the picture. Now you suddenly need to do something before this method, such as a log, and then a log after compression.
you might think that it would be OK to just change this method, yes, but you might want to call this class method in some places without having to print the log.
you say it again, then write another class. of course, also can, but you think, compressed picture of the code is the same, then you will not be to maintain two sets of the same code, no no no, too laborious.
at this point you may not forget, that with inheritance, inherit the original class , rewrite This compression method, super before printing a log,super after printing a log. Well, this is doable, but maybe I can't use the other methods in this class, I just use this compression method, the inheritance is not too heavy.
What's the alternative?
In this way, you can use the proxy mode. Come and see an example together.
I have an interface:
No problem, there's an implementation class:
There is no problem, the direct instantiation of the can be used.
What if I want to add something before then?
Two ways:
Static proxy
In writing a class:
At this point in the call:
Look at the results:
Dynamic Agent
Another is the dynamic agent, you can directly use the JDK dynamic proxy mode (hook with more, the article will be said later).
Dynamic proxy, need to use the concept of reflection, about reflection, you can refer to my previous article (I will be attached to the bottom).
First, we don't need to implement this interface. Just need to implement an interface in Java Invocationhandler
Then instantiate using the proxy class:
Take a look at the effect:
Nutshell
Proxy is a method interceptor, the first parameter is ClassLoader, the second parameter is the class of interception, Invocationhandler is the interception interface, in Invocationhandler can be re-implemented this method.
(ext.) "Android those high-forcing" Invocationhandler and proxy mode