Java Dynamic proxy implementation

Source: Internet
Author: User

Dynamic proxy, as an extension form of proxy mode, is widely used in the design and development of frameworks (especially the AOP-based frameworks). This article will explain the implementation process of Java Dynamic proxy through examples.

Tip: This article is a little difficult. You must have basic knowledge about Agent Mode.,.

 

NormallyEach proxy class will generate a class file after compilation. The interfaces implemented by the proxy class and the proxies are fixed. Such proxies are called static proxies). Is there a mechanism?Allows the system to dynamically create proxy classes during runtime? The answer is what we will introduce in this article.Dynamic proxy). Dynamic proxy is a relatively advanced proxy mode. It plays an important role in transaction management, AOP (Aspect-orientedprogramming, Aspect-Oriented Programming) and other fields.

 

In the traditional proxy mode, the client calls the request () method of the realsubject class through the proxy class, and can encapsulate other methods (such as prerequest () and postrequest () in the proxy class () ). If the proxy mode is used in this methodBoth the proxy class and the real theme class should already exist in advance. Both the proxy class interface and the proxy method have been explicitly specified, if you need to provide proxy classes for different real theme classes or delegate different methods in a real theme class, you need to add new proxy classes, which will lead to a sharp increase in the number of classes in the system, therefore, we need to find a way to reduce the number of classes in the system. Dynamic proxy allows the system to dynamically create proxy classes based on actual needs, so that the same proxy class can proxy multiple real theme classes and proxy different methods.

 

Since JDK 1.3, the Java language provides support for dynamic proxies. Some classes in the Java. Lang. Reflect package must be used to implement dynamic proxies in Java. The following is a brief description:

 

(1) proxy class

The proxy class provides a method for creating dynamic proxy classes and instance objects. It is the parent class of the created dynamic proxy class. The most common method is as follows:

  • Public static class <?> Getproxyclass (classloader loader, class <?>... Interfaces): This method is used to return a class-type proxy class. In the parameter, you must provide the class loader and specify the proxy interface array (consistent with the interface list of the real topic class ).
  • Public static object newproxyinstance (classloader loader, class <?> [] Interfaces, invocationhandler h): This method is used to return an instance of the dynamically created proxy class. In the method, the first parameter loader indicates the class loader of the proxy class, the second parameter interfaces indicates the list of interfaces implemented by the proxy class (consistent with the list of interfaces of the real topic class), and the third parameter H indicates the designated call handler class.

(2) invocationhandler Interface

Invocationhandler interface is the implementation interface of the proxy handler class, which serves as the public parent class of the proxy instance caller handler, each proxy instance can provide a specific caller (subclass of the invocationhandler interface ). The following method is described in this interface:

  • Public object invoke (objectproxy, method, object [] ARGs): This method is used to process method calls to proxy instances and return corresponding results, this method is automatically called when a service method in a proxy instance is called. The invoke () method contains three parameters. The first parameter proxy indicates the instance of the proxy class, the second parameter method indicates the method that requires proxy, and the third parameter ARGs indicates the parameter array of the proxy method.

The dynamic proxy class must specify the interface of the real topic class of the proxy at runtime. When the client calls the method of the dynamic proxy object, the call request will automatically forward the request to the invocationhandler object's invoke () method, the invoke () method is used to process requests in a unified manner.

 

Here is a simple example to learn how to use the dynamic proxy mode:

Sunny software wants to add method call logs for Dao in the data access layer of the company's OA system, record the time and result of each method call, And now uses dynamic proxy for design and implementation.

 

The complete code of this instance is as follows:

Import Java. lang. reflect. proxy; import Java. lang. reflect. invocationhandler; import Java. lang. reflect. invocationtargetexception; import Java. lang. reflect. method; import Java. util. calendar; import Java. util. gregoriancalendar; // abstract userdao: Abstract topic role interface abstractuserdao {public Boolean finduserbyid (string userid);} // abstract documentdao: Abstract topic role interface abstractdocumentdao {public Boolean deletedocumentbyid (string Entid);} // specific userdao class: real topic role class userdao implements abstractuserdao {public Boolean finduserbyid (string userid) {If (userid. equalsignorecase ("Zhang Wuji") {system. out. println ("querying user information with ID + userid +" is successful! "); Return true;} else {system. Out. println (" An error occurred while querying user information whose ID is "+ userid +! "); Return false ;}}// specific documentdao class: real topic role class documentdao implements abstractdocumentdao {public Boolean deletedocumentbyid (string effecentid) {If (effecentid. equalsignorecase ("d001") {system. out. println ("deleting document information with ID =" + entid + "is successful! "); Return true;} else {system. Out. println (" An error occurred while deleting the document whose ID is "+ entid +! "); Return false ;}}// custom request processing program class daologhandler implements invocationhandler {private calendar; private object; Public daologhandler () {} // custom constructor with parameters, used to inject a real theme object public daologhandler (Object object) {This. object = object;} // implements the invoke () method, and calls the public object invoke (Object proxy, method, object [] ARGs) method defined in the real topic class) throws throwable {beforeinvoke (); object result = method. invo Ke (object, argS); // call afterinvoke (); return NULL;} // record method call time public void beforeinvoke () {calendar = new gregoriancalendar (); int hour = calendar. get (calendar. hour_of_day); int minute = calendar. get (calendar. minute); int second = calendar. get (calendar. second); string time = hour + ":" + minute + ":" + second; system. out. println ("call time:" + time);} public void afterinvoke () {system. out. println (" Method call ended! ");}}

Write the following client test code:

Class client {public static void main (string ARGs []) {invocationhandler handler = NULL; abstractuserdao userdao = new userdao (); handler = new daologhandler (userdao); abstractuserdao proxy = NULL; // dynamically create a proxy object to proxy a real theme object of the abstractuserdao type proxy = (abstractuserdao) proxy. newproxyinstance (abstractuserdao. class. getclassloader (), new class [] {abstractuserdao. class}, Handler); proxy. finduserbyid ("Zhang Wuji"); // call the Business Method System of the proxy object. out. println ("----------------------------"); abstractdocumentdao docdao = new documentdao (); handler = new daologhandler (docdao); abstractdocumentdao proxy_new = NULL; // dynamically create a proxy object, used to represent a real theme object of the abstractdocumentdao type proxy_new = (abstractdocumentdao) proxy. newproxyinstance (Abstract documentdao. class. getclassloader (), new class [] {abstractdocumentdao. class}, Handler); proxy_new.deletedocumentbyid ("d002"); // call the Business Method of the proxy object }}

Compile and run the program. The output result is as follows:

Call time: 13: 47: 14

User information with the ID of zhangwuji is queried successfully!

Method call ended!

------------------------------

Call time: 13: 47: 14

An error occurred while deleting the document with the ID of d002!

Method call ended!

By using dynamic proxy, we can implement unified proxy and centralized control over multiple real themes.

Note: The dynamic proxy provided by JDK can only proxy one or more interfaces. to dynamically proxy specific classes or abstract classes, you can use tools such as cglib (code generation library, cglib is a code generation package with powerful functions, performance, and quality. It is widely used in many AOP frameworks. You can refer to relevant materials to learn cglib.

[Author: Liu Wei http://blog.csdn.net/lovelion]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.