The current Java development package includes support for dynamic proxies, but its implementation only supports the implementation of interfaces. The main implementation is through the java. Lang. Reflect. proxy class and Java. Lang. Reflect. invocationhandler interface. The proxy class is mainly used to obtain dynamic proxy objects. The invocationhandler interface is used to constrain the implementation of callers. The following describes the business methods defined by the helloworld interface. helloworldimpl is the implementation of the helloworld interface and helloworldhandler is the implementation of the invo.
Code Service Interface:
| Public interface helloworld {Void sayhelloworld ();} |
Business interface implementation:
| Public class helloworldimpl implements helloworld {
Public void sayhelloworld (){System. Out. println ("Hello world! ");}}
|
To implement invocationhandler, you need to add a processing job before and after the interface method call. Here, only two strings are output to the background before and after the method call. The Code is as follows:
| Import java. Lang. Reflect. invocationhandler; import java. Lang. Reflect. method;
Public class helloworldhandler implements invocationhandler { // Original object to be proxy Private object objoriginal; /** * Constructor. * @ Param OBJ The original object to be proxy. */ Public helloworldhandler (Object OBJ ){ This. objoriginal = OBJ; }
Public object invoke (Object proxy, method, object [] ARGs) Throws throwable { Object result; // Before method call Dobefore (); // Method of calling the original object Result = method. Invoke (this. objoriginal, argS ); // After the method is called Doafter (); Return result; } Private void dobefore (){ System. Out. println ("before method invoke! "); } Private void doafter (){ System. Out. println ("after method invoke! "); } }
|
Test code:
| Import java. Lang. Reflect. invocationhandler; import java. Lang. Reflect. proxy;
Public class test {
Public static void main (string [] ARGs ){
Helloworld hW = new helloworldimpl (); Invocationhandler handler = new helloworldhandler (HW ); Helloworld proxy = (helloworld) proxy. newproxyinstance ( HW. getclass (). getclassloader (), HW. getclass (). getinterfaces (), Handler );
Proxy. sayhelloworld (); } }
|
Ø First, obtain the implementation object of a business interface;
Ø Get an invocationhandler implementation. Here is the helloworldhandler object;
Ø Create a dynamic proxy object;
Ø Call the sayhelloworld () method through a dynamic proxy object. At this time, two strings are output before and after the original object helloworldimpl. sayhelloworld () method. The output of the running test class is as follows:
| Before method invoke! Hello world! After method invoke! |
There are many method call codes in the test class. In our actual application, we can use the configuration file to simplify the client call implementation. In addition, you can use dynamic proxies to implement simple AOP.