Proxy: Design mode
A proxy is a common design pattern designed to provide a proxy for other objects to control access to an object. The proxy class is responsible for preprocessing the message for the delegate class, filtering the message and forwarding the message, and subsequent processing after the message is delegated to the class.
650) this.width=650; "src=" Https://www.ibm.com/developerworks/cn/java/j-lo-proxy1/image001.png "alt=" Figure 1. Proxy mode "/>
In order to maintain the consistency of the behavior, the proxy class and the delegate class usually implement the same interface, so there is no difference between the visitors. Through the intermediate layer of proxy class, the direct access to delegate class object can be controlled effectively, and the delegate class object can be hidden and protected well, and space is reserved for implementing different control strategies, which gives more flexibility in design. The Java dynamic agent mechanism is a clever way to practice the design concept of the proxy mode in near perfect fashion.
First, create the proxy class and interface
To create an interface:
Package com.nudt.design.proxy;/** * Created by Jeffrey on 15-12-2. */public interface Moveable {public void move ();
To create a proxy class:
package com.nudt.design.proxy;import java.util.random;/** * Created by jeffrey on 15-12-2. */public class Car implements moveable{ @Override public void move () { try { thread.sleep (New random (). Nextint (+)); } catch (interruptedexception e) { e.printstacktrace (); } } //system.out.println ("");}
Second, create a class that implements the Invocationhandler interface, and implement the Invoke method for that interface. Java.lang.reflect.InvocationHandler: This is the call processor interface, which customizes an invoke method that centralizes the method invocation on the dynamic proxy class object, typically implementing proxy access to the delegate class in the method.
Listing 2. The core approach of Invocationhandler
This method is responsible for centralizing all method calls on the dynamic proxy class. The first parameter is both a proxy class instance, the second parameter is the method object being called//the third method is the call parameter. The calling processor is preprocessed or dispatched to the delegate class instance based on these three parameters to execute object invoke (object proxy, method, object[] args) Each time a dynamic proxy class object is generated, you need to specify a call processor object that implements the interface (see the third parameter of Proxy static method 4).
package com.nudt.design.jdkproxy;import java.lang.reflect.invocationhandler;import Java.lang.reflect.method;/** * created by jeffrey on 15-12-3. */public class timehandler implements invocationhandler { private object target; public timehandler (Object target) { this.target = target; } /* * parameters: * o: Proxy Object * method: The method of the Proxied object * objects: Parameter * Return of the proxy object method: * object object, which is the return value of the object method, * */ @Override public object invoke (Object o, method method, object[] objects)  THROWS&NBSp throwable { long starttime = System.currenttimemillis (); method.invoke (target); long endtime = system.currenttimemillis ();       SYSTEM.OUT.PRINTLN ("Car End Drive, time" + (Endtime - starttime) + "millisecond"); return null; }}
Third, in the test main function, call the static method of proxy, create a proxy instance, the proxy instance is also an object that implements the interface implemented by the proxy class. Java.lang.reflect.Proxy: This is the main class of the Java Dynamic Agent mechanism, which provides a set of static methods for dynamically generating proxy classes and their objects for a set of interfaces.
Listing 1. static method of Proxy
Method 1: The method is used to get the specified proxy object associated with the calling processor static Invocationhandler Getinvocationhandler (object proxy)//method 2: The method is used to obtain the class object of the dynamic proxy class associated with the specified class loader and a set of interfaces static class Getproxyclass (ClassLoader loader, class[] interfaces)//method 3: This method is used to determine whether the specified class object is a dynamic proxy class static Boolean Isproxyclass (class CL)//Method 4: This method is used to generate a dynamic proxy class instance static object for the specified class loader, a set of interfaces, and the calling processor Newproxyinstance (ClassLoader loader, class[] interfaces, Invocationhandler h)
Iv. methods for invoking Proxied objects through proxy instances
The three or four-step code is as follows:
package com.nudt.design.jdkproxy;import com.nudt.design.proxy.car;import com.nudt.design.proxy.moveable;import java.lang.reflect.proxy;/** * created by jeffrey on 15-12-3. */public class test { public Static void main (String[] args) { // Defines a proxy class car car = new car (); //gets the class name of the proxy class Class<?> cls = car.getclass (); //Create a dynamic agent event handler timehandler h = new timehandler (CAR); //Create a proxy m /* parameter: * class Loader &List of interfaces implemented by nbsp; * * Event handler * return value: * dynamically generated proxy objects (also implemented as interfaces with proxy objects) * */ Moveable m = (moveable) proxy.newproxyinstance ( Cls.getclassloader (), Cls.getinterfaces (), h); //Run Agent m.move (); }}
Where Java.lang.ClassLoader: This is the class loader class, which is responsible for loading the bytecode of the class into the Java Virtual Machine (JVM) and defining the class object for it, and then the class can be used. Proxy static method generating dynamic proxy classes also need to be loaded through a class loader to use, and the only difference from the normal class is that its bytecode is generated dynamically by the JVM at runtime rather than pre-existing in any. class file.
Now let's look at some of the features of the Java dynamic agent mechanism.
First, there are some characteristics of the dynamically generated proxy class itself. 1) Package: If the interface being proxied is public, then it will be defined in the top-level package (that is, the package path is empty), if there is a non-public interface in the Proxied interface (because the interface cannot be defined as protect or private, it is the default except public) Package access level), then it will be defined in the packet where the interface is located (assuming that a non-public interface A is represented in the Com.ibm.developerworks package, the package that contains the newly generated proxy class is Com.ibm.developerworks), the purpose of this design is to ensure that the dynamic proxy class is not able to be successfully defined and accessed due to the problem of package management; 2) class modifier: The proxy class has the final and public modifiers, which means that it can be accessed by all classes , but cannot be re-inherited; 3) class name: The format is "$ProxyN", where N is an increment of Arabic numerals, representing the proxy class nth generation of dynamic proxy class, it is worth noting that not every time the static method call proxy to create a dynamic proxy class will increase the N value, The reason is that if you attempt to create a dynamic proxy class repeatedly for the same set of interfaces (including the order of the interfaces), it will be wise to return the class object of the proxy class that was previously created, instead of trying to create a completely new proxy class, which saves unnecessary code duplication and increases the efficiency of the proxy class creation. 4) class inheritance relationship: The inheritance relationship of this class
650) this.width=650; "src=" Https://www.ibm.com/developerworks/cn/java/j-lo-proxy1/image002.png "alt=" Figure 2. Inheritance diagram for dynamic proxy classes "/>
As the diagram shows, the proxy class is its parent class, and this rule applies to all dynamic proxy classes created by proxy. And the class implements a set of interfaces that it proxies, which is why it can be safely typed to the root cause of an interface it proxies.
Now let's look at some of the characteristics of proxy class instances. Each instance is associated with a calling processor object, which can be getinvocationhandler to get the calling processor object of the proxy class instance through the static method provided by proxy. When a method declared in the interface of its proxy is invoked on a proxy class instance, these methods will eventually be executed by the Invoke method of the calling processor, in addition, it is worth noting that there are three methods in the root class java.lang.Object of the proxy class that are also dispatched to the calling processor's invoke Method execution, which are hashcode,equals and toString, may be due to the fact that these methods are public and non-final types, can be overridden by proxy classes, and because these methods tend to present a characteristic attribute of a class with a certain degree of sensitivity, Therefore, in order to ensure that the proxy class and the delegation class external consistency, these three methods should also be assigned to the delegate class execution. When a set of interfaces for an agent has a repeating method and the method is called, the proxy class always gets the method object from the first interface and assigns it to the calling processor, regardless of whether the proxy class instance is externally referenced in the form of that interface (or a sub-interface that inherits from the interface). Because it is not possible to differentiate its current referenced type within a proxy class.
Then, let's look at the characteristics of a group of interfaces that are being proxied. First, be aware that you cannot have duplicate interfaces to avoid compilation errors when the dynamic proxy class code is generated. Second, these interfaces must be visible to the class loader, or the class loader will not be able to link them, causing the class definition to fail. Again, all non-public interfaces that need to be proxied must be in the same package, or the proxy class generation will fail. Finally, the number of interfaces cannot exceed 65535, which is the limit set by the JVM.
Finally, let's look at the characteristics of exception handling. From the method that invokes the processor interface declaration, it can be seen theoretically that it can throw any type of exception, because all exceptions are inherited from the Throwable interface, but is it true? The answer is no, because we must obey an inheritance principle: When a subclass overrides a parent or implements a parent interface, the exception thrown must be within the list of exceptions supported by the original method. So while the calling processor is theoretically capable, it is actually often limited unless the method in the parent interface supports throwing Throwable exceptions. So what if the Invoke method does produce an exception that is not supported in the interface method declaration? Rest assured, the Java dynamic proxy class has designed a workaround for us: it will throw a undeclaredthrowableexception exception. This exception is a runtimeexception type, so it does not cause a compilation error. With the exception's Getcause method, you can also get the original unsupported exception object for error diagnosis.
Dynamic proxy for Java design patterns