Implementation of dynamic Agent in Java

Source: Internet
Author: User

As an extended form of proxy mode, dynamic agent is widely used in the design and development of framework (especially AOP-based framework), this paper will explain the implementation process of Java Dynamic Agent through examples.

friendly hint: This article is slightly difficult, the reader should have the basic knowledge of the agent model .

Typically, each proxy class in the proxy pattern generates a class file after compilation, and the interface that the proxy class implements and the methods that it proxies are fixed, and this proxy is called a static proxy. . So is there a mechanism that allows the system to dynamically create proxy classes at run time ? The answer is the dynamic proxy that will be introduced in this article. Dynamic agent is a kind of advanced proxy mode, which plays an important role in transaction management,AOP (aspect-orientedprogramming, aspect-oriented programming) and other fields.

In traditional proxy mode, the client invokes the request () method of the Realsubject class through the proxy class , and it can encapsulate other methods in the proxy class (such as prerequest () and postrequest (), etc.). If the proxy mode is used in this way, then both the proxy class and the real topic class should be pre-existing, the interface of the proxy class and the proxy method are clearly specified, if you need to provide a proxy class for different real topic classes or proxy a different method in a real topic class, you need to add a new proxy class. This results in a dramatic increase in the number of classes in the system, so you need to find ways to reduce the number of classes in your system. Dynamic proxy allows the system to dynamically create proxy classes based on actual needs, allowing the same proxy class to proxy multiple different real-world topic classes and to broker different methods.

starting with JDK 1.3, theJava language provides support for dynamic proxies, and some classes in the Java.lang.reflect package are needed for the Java language to implement dynamic proxies, which are briefly described below:

(1) proxy class

The proxy class provides a method for creating dynamic proxy classes and instance objects, which is the parent class of the dynamic proxy class that is created, and it is most commonly used in the following ways:

    • public static class<?> Getproxyclass (ClassLoader loader,class<?> ... interfaces): This method is used to return a Class type, the class loader needs to be provided in the parameters and an array of interfaces for the proxy must be specified (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 a dynamically created proxy class, in which the first parameter loader represents the class loader of the proxy class, and the second parameter interfaces represents the list of interfaces implemented by the proxy class (consistent with the interface list of the real topic Class), and the third parameter H represents the calling handler class that is assigned.

(2) Invocationhandler interface

The Invocationhandler interface is an implementation interface of the proxy handler class that acts as the public parent class of the calling processor for the proxy instance, and each instance of the proxy class can provide a related specific call handler ( Sub-class of the Invocationhandler interface). The following methods are declared in this interface:

    • Public Object Invoke (ObjectProxy, method, object[] args): This method is used to process a method call to an instance of a proxy class and returns the corresponding result, which is called automatically when a business method in a proxy instance is called. The Invoke () method contains three parameters, where the first parameter proxy represents an instance of the proxy class, the second parameter means the method that requires the proxy, and the third parameter, args, represents an array of arguments for the proxy method.

The dynamic proxy class needs to specify the interface of the actual subject class at run time, and when the client invokes the method of the dynamic proxy object, the calling request automatically forwards the request to the Invoke () method of the Invocationhandler object, by the Invoke () method to achieve uniform processing of requests.

Here's a simple example to learn how to use dynamic Proxy mode:

Sunny software company for the company OA system data Access Layer DAO Add method call log, record each method is called time and call result, now use dynamic Agent to design and implement.

The complete code for this example is as follows:

[Java]View plain copy
  1. Import Java.lang.reflect.Proxy;
  2. Import Java.lang.reflect.InvocationHandler;
  3. Import java.lang.reflect.InvocationTargetException;
  4. Import Java.lang.reflect.Method;
  5. Import Java.util.Calendar;
  6. Import Java.util.GregorianCalendar;
  7. Abstract Userdao: Abstract Theme roles
  8. Interface Abstractuserdao {
  9. Public Boolean Finduserbyid (String userId);
  10. }
  11. Abstract Documentdao: Abstract Theme roles
  12. Interface Abstractdocumentdao {
  13. Public Boolean Deletedocumentbyid (String documentid);
  14. }
  15. Specific Userdao classes: real-World theme roles
  16. Class Userdao implements Abstractuserdao {
  17. Public Boolean Finduserbyid (String userId) {
  18. if (userid.equalsignorecase ("Zhang Mowgli")) {
  19. SYSTEM.OUT.PRINTLN ("Query ID for" + userId + "user information succeeded!)  ");
  20. return true;
  21. }
  22. else {
  23. SYSTEM.OUT.PRINTLN ("Query ID for" + userId + "user information failed!)  ");
  24. return false;
  25. }
  26. }
  27. }
  28. Specific Documentdao classes: real-World theme roles
  29. Class Documentdao implements Abstractdocumentdao {
  30. Public Boolean Deletedocumentbyid (String documentid) {
  31. if (documentid.equalsignorecase ("D001")) {
  32. System.out.println ("Delete the Document information with ID" + DocumentID + "Success!)  ");
  33. return true;
  34. }
  35. else {
  36. System.out.println ("Delete Document information with ID" + DocumentID + "failed!)  ");
  37. return false;
  38. }
  39. }
  40. }
  41. Custom Request Handler Classes
  42. Class Daologhandler implements Invocationhandler {
  43. private Calendar Calendar;
  44. private Object object;
  45. Public Daologhandler () {
  46. }
  47. //Custom parameter constructor for injecting a real subject object that needs to provide a proxy
  48. Public Daologhandler (Object object) {
  49. This.object = object;
  50. }
  51. //Implement the Invoke () method and invoke the method defined in the real topic class
  52. Public object Invoke (Object proxy, Method method, object[] args) throws Throwable {
  53. Beforeinvoke ();
  54. Object result = Method.invoke (object, args); //Forwarding call
  55. Afterinvoke ();
  56. return null;
  57. }
  58. //Record method call time
  59. public void Beforeinvoke () {
  60. Calendar = new GregorianCalendar ();
  61. int hour = Calendar.get (Calendar.hour_of_day);
  62. int minute = Calendar.get (Calendar.minute);
  63. int second = Calendar.get (Calendar.second);
  64. String time = hour + ":" + Minute + ":" + second;
  65. System.out.println ("Call time:" + times);
  66. }
  67. public void Afterinvoke () {
  68. System.out.println ("method call ends!  " );
  69. }
  70. }

Write the following client test code:

[Java]View plain copy
  1. Class Client {
  2. public static void Main (String args[]) {
  3. Invocationhandler handler = null;
  4. Abstractuserdao Userdao = new Userdao ();
  5. Handler = new Daologhandler (Userdao);
  6. Abstractuserdao proxy = null;
  7. //Create a proxy object dynamically to proxy a real-world subject object of type Abstractuserdao
  8. Proxy = (Abstractuserdao) proxy.newproxyinstance (Abstractuserdao. Class.getclassloader (), new Class[]{abstractuserdao.   Class}, Handler);
  9. Proxy.finduserbyid ("Zhang Mowgli"); //Calling the proxy object's business method
  10. System.out.println ("------------------------------");
  11. Abstractdocumentdao Docdao = new Documentdao ();
  12. Handler = new Daologhandler (Docdao);
  13. Abstractdocumentdao proxy_new = null;
  14. Dynamically create proxy objects to proxy a real-world subject object of type Abstractdocumentdao
  15. Proxy_new = (Abstractdocumentdao) proxy.newproxyinstance (Abstract Documentdao. Class.getclassloader (), new Class[]{abstractdocumentdao.   Class}, Handler);
  16. Proxy_new.deletedocumentbyid ("D002"); //Calling the proxy object's business method
  17. }
  18. }

Compile and run the program with the following output:

Call time:13:47:14

Query ID for Zhang Mowgli user information success!

Method call Ends!

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

Call time:13:47:14

failed to delete Document information with ID D002!

Method call Ends!

by using dynamic proxies, we can implement unified proxy and centralized control over multiple real-world topic classes.

Note: The dynamic agent provided in the JDK can only proxy one or more interfaces, if you need to dynamically proxy specific classes or abstract classes, you can use Cglib (Code Generation Library) and other tools, Cglib is a more powerful, The code generation package with good performance and quality is widely used in many AOP frameworks, so you can learn cglib by yourself.

Implementation of dynamic Agent in Java

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.