Protection proxy
Before and after a method is called, perform some actions.
A dynamic proxy is called a dynamic proxy because its class is created only at runtime.
Logs, connections, transactions,
Java in Java. lang. the reflect package has its own Proxy Support. With this package, you can dynamically create a proxy class at runtime to implement one or more interfaces, and forward the call of the method to the class you specified. Because the actual proxy class is created at runtime, we call this Java technology dynamic proxy.
Java creates a proxy class for you. Because proxy is not directly implemented by you, you should put the proxy that the proxy executes in invocationhandler.
Invocationhandler is used to respond to any call of the proxy. You can think of invocationhandler as the object for the actual work of the request after the proxy receives the method call.
1. Implement the invocationhandler interface to implement its invoke method. This method is the method you want to proxy. You can wrap this method before and after the code.
Public object invoke (Object proxy, method, object [] ARGs) throws illegalaccessexception {};
2. Create a dynamic proxy class and an object is required.
(Personbean) proxy. newproxyinstance (person. getclass (). getclassloader (), person. getclass (). getinterfaces (), new ownerinvocationhandler (person ));
Demo:
Getproxymethod (). XXX (). Then, the invoke will be executed in invocationhandler.
1.
2.
3.
1. Is there a way to know if a class is a proxy class? Yes. The proxy class has a static method called isproxyclass (). returns true, indicating that this is a dynamic proxy class.
2. Are there any restrictions on the Interface Type passed in newproxyinstance?
There are some restrictions. First, we always pass the newproxyinstance () interface array. This array can only contain interfaces and classes. If the interface is not public, it must belong to the same package.
The method with the same name and parameter is not allowed. There are some more subtle restrictions. You should take a good look at the javadoc files.
Design Pattern (11)-Dynamic proxy in proxy pattern