Dynamic Agent for Java

Source: Internet
Author: User

Proxy mode
Proxy mode is a common Java design pattern, his characteristic is that the proxy class and the delegate class have the same interface, the proxy class is mainly responsible for the delegate class preprocessing messages, filtering messages, forwarding messages to the delegate class, and post-processing messages. There is usually an association between the proxy class and the delegate class, and the object of a proxy class is associated with an object of a delegate class, and the object of the proxy class does not actually implement the service, but instead provides a specific service by invoking the related method of the object of the delegate class.
The proxy class can be divided into two types according to the agent's creation period.
Static proxy: The source code is generated automatically by the programmer or a specific tool, and then compiled. Before the program runs, the. class file for the proxy classes already exists.
Dynamic Agent: When the program is running, it is created dynamically using the reflection mechanism.

First look at the static proxy:
1, Count.java

Java code:
  1. Package Net.battier.dao;
  2. /**
  3. * Define an Account interface
  4. *
  5. * @author Administrator
  6. *
  7. */
  8. Public interface Count {
  9. //View account method
  10. public void Querycount ();
  11. //Modify account method
  12. public void Updatecount ();
  13. }


2, Countimpl.java

Java code:
  1. Package Net.battier.dao.impl;
  2. Import Net.battier.dao.Count;
  3. /**
  4. * Delegate Class (Contains business logic)
  5. *
  6. * @author Administrator
  7. *
  8. */
  9. Public class Countimpl implements Count {
  10. @Override
  11. public void Querycount () {
  12. System.out.println ("View account Method ...");
  13. }
  14. @Override
  15. public void Updatecount () {
  16. System.out.println ("Modify Account Method ...");
  17. }
  18. }
  19. , Countproxy.java
  20. Package Net.battier.dao.impl;
  21. Import Net.battier.dao.Count;
  22. /**
  23. * This is a proxy class (Enhanced Countimpl implementation Class)
  24. *
  25. * @author Administrator
  26. *
  27. */
  28. Public class Countproxy implements Count {
  29. private Countimpl Countimpl;
  30. /** 
  31. * Override the default constructor
  32. *
  33. * @param Countimpl
  34. */
  35. Public Countproxy (Countimpl countimpl) {
  36. This.countimpl = Countimpl;
  37. }
  38. @Override
  39. public void Querycount () {
  40. System.out.println ("before transaction processing");
  41. //method of invoking the delegate class;
  42. Countimpl.querycount ();
  43. System.out.println ("after transaction processing");
  44. }
  45. @Override
  46. public void Updatecount () {
  47. System.out.println ("before transaction processing");
  48. //method of invoking the delegate class;
  49. Countimpl.updatecount ();
  50. System.out.println ("after transaction processing");
  51. }
  52. }

3, Testcount.java

Java code:
  1. Package net.battier.test;
  2. Import Net.battier.dao.impl.CountImpl;
  3. Import Net.battier.dao.impl.CountProxy;
  4. /**
  5. * Test Count class
  6. *
  7. * @author Administrator
  8. *
  9. */
  10. Public class Testcount {
  11. public static void Main (string[] args) {
  12. Countimpl Countimpl = new Countimpl ();
  13. Countproxy countproxy = new Countproxy (Countimpl);
  14. Countproxy.updatecount ();
  15. Countproxy.querycount ();
  16. }
  17. }

Observation code can find that each proxy class can only serve one interface, so that the development of the program will inevitably generate too many agents, and all the agent operation in addition to the method called, the other operations are the same, then it must be duplicated code. The best way to solve this problem is to complete the proxy function through a proxy class, which must be done using dynamic proxy.


Let's take a look at the dynamic proxy:
The JDK dynamic agent contains a class and an interface:
Invocationhandler Interface:
Public interface Invocationhandler {
public object Invoke (Object Proxy,method method,object[] args) throws Throwable;
}
Parameter description:
Object proxy: Refers to the objects being proxied.
Method: Methods to invoke
object[] args: Parameters required for method invocation

The subclass of the Invocationhandler interface can be imagined as a proxy's final operation class, replacing the Proxysubject.

Proxy class:
The proxy class is an action class that specifically completes the proxy, which can be used to dynamically generate an implementation class for one or more interfaces, which provides the following operations:
public static Object newproxyinstance (ClassLoader loader, class<?>[] interfaces,
Invocationhandler h)
Throws IllegalArgumentException
Parameter description:
ClassLoader Loader: Class loader
Class<?>[] Interfaces: Get all the interfaces
Invocationhandler h: Get subclass instance of Invocationhandler interface

Ps: Class Loader
In the proxy class in the Newproxyinstance () method requires an instance of the ClassLoader class, ClassLoader actually corresponds to the class loader, in Java, there are three kinds of loaders;
Booststrap ClassLoader: This loader is written in C + + and is not visible in general development;
Extendsion ClassLoader: Used to load the extension class, generally corresponding to the class in the Jre\lib\ext directory;
Appclassloader: (default) Loads the class specified by Classpath, which is most commonly used as an loader.

Dynamic Agent
Compared with the static proxy class, dynamic proxy class, the bytecode of dynamic proxy class is generated dynamically by the Java reflection mechanism when the program runs, without the programmer writing its source code manually. The dynamic proxy class not only simplifies programming, but also improves the scalability of the software system, because the Java reflection mechanism can generate any type of dynamic proxy class. The proxy class and the Invocationhandler interface in the Java.lang.reflect package provide the ability to generate dynamic proxy classes.

Dynamic Proxy Example:
1, Bookfacade.java

Java code
    1. Package Net.battier.dao;
    2. Public interface Bookfacade {
    3. public void Addbook ();
    4. }

2, Bookfacadeimpl.java

Java code
  1. Package Net.battier.dao.impl;
  2. Import Net.battier.dao.BookFacade;
  3. Public class Bookfacadeimpl implements Bookfacade {
  4. @Override
  5. public void Addbook () {
  6. System.out.println ("Add Book Method ...  ");
  7. }
  8. }
  9. , Bookfacadeproxy.java
  10. Package net.battier.proxy;
  11. Import Java.lang.reflect.InvocationHandler;
  12. Import Java.lang.reflect.Method;
  13. Import Java.lang.reflect.Proxy;
  14. /**
  15. * JDK Dynamic Proxy proxy class
  16. *
  17. * @author Student
  18. *
  19. */
  20. Public class Bookfacadeproxy implements Invocationhandler {
  21. private Object target;
  22. /** 
  23. * Binds the delegate object and returns a proxy class
  24. * @param target
  25. * @return
  26. */
  27. Public object bind (object target) {
  28. this.target = target;
  29. //Get proxy object
  30. return Proxy.newproxyinstance (Target.getclass (). getClassLoader (),
  31. Target.getclass (). Getinterfaces (), this ); //To bind the interface (this is a flaw, cglib compensates for this flaw)
  32. }
  33. @Override
  34. /** 
  35. * Call method
  36. */
  37. Public object Invoke (Object proxy, Method method, object[] args)
  38. throws Throwable {
  39. Object result=null;
  40. System.out.println ("things start");
  41. //Execution Method
  42. Result=method.invoke (target, args);
  43. System.out.println ("End of Thing");
  44. return result;
  45. }
  46. }

3, Testproxy.java

Java code
  1. Package net.battier.test;
  2. Import Net.battier.dao.BookFacade;
  3. Import Net.battier.dao.impl.BookFacadeImpl;
  4. Import Net.battier.proxy.BookFacadeProxy;
  5. Public class Testproxy {
  6. public static void Main (string[] args) {
  7. Bookfacadeproxy proxy = new Bookfacadeproxy ();
  8. Bookfacade bookproxy = (bookfacade) proxy.bind (new Bookfacadeimpl ());
  9. Bookproxy.addbook ();
  10. }
  11. }

However, the dynamic proxy of the JDK relies on the interface, and if some classes do not implement the interface, then the JDK proxy cannot be used, which will use the Cglib dynamic proxy.

Dynamic Agent for 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.