Java Dynamic Agent

Source: Internet
Author: User
Tags ming throwable

Proxy mode : The common Java design pattern, characterized by the same interface between the proxy class and the delegate class, the proxy class is responsible for preprocessing the information, filtering information, transferring the message to the delegate class and processing the message afterwards. There is usually an association between a proxy class and a delegate class, and the object of the proxy class does not actually implement the service, but rather the method that invokes the object of the delegate class.

By the time the agent was created, the proxy classes were divided into:

Static proxy: The source code is generated automatically by the programmer or a specific tool, and then compiled. The. class file for the proxy classes already exists before the program runs.

Dynamic Agent: When the program is running, it is created dynamically using the reflection mechanism.

First look at the static proxy:

1, Count.java

  Package Net.battier.dao;

    1. Public interface Count {
    2. View account Methods
    3. Public void Querycount ();
    4. Modify Account Method
    5. Public void Updatecount ();
    6. }


2, Countimpl.java

  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

    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. }

As can be seen from the above, the disadvantage of static proxy is that each proxy class can only serve an interface, so that the program development, will inevitably generate too many agents, duplicate code appears. The best way to solve this problem is to complete the proxy function through a proxy class, which must be done using dynamic proxy.

Then look at the dynamic agent:

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

1.Person class

Package cn.itcast.proxy;

Public interface Person {

public abstract string Sing (string name);

Public abstract string Dance (string name);

}

2.Liming class

Package cn.itcast.proxy;

public class Liming implements person {

@Override
public string Sing (string name) {
System.out.println ("Li Ming Sings" +name+ "Song!! ");
Return "Thank you";
}


@Override
public string Dance (string name) {
System.out.println ("Li Ming jumps" +name+ "Dance!! ");
Return "Kiss";
}
}

3. Dynamic proxy class

Package cn.itcast.proxy;

Import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Method;
Import Java.lang.reflect.Proxy;

public class Limingproxy {
Private person liming=new liming ();

Public Person Createproxy () {
return (person) proxy.newproxyinstance (LimingProxy.class.getClassLoader (), Liming.getclass (). Getinterfaces (), New Invocationhandler () {

@Override
/**
* Proxy: Pass in the agent object itself
* Method: Represents the methods currently called
* Args: Parameters of the Calling method
*/
public object invoke (object proxy, Method method, object[] args)
Throws Throwable {
String Methosname=method.getname ();
if (Methosname.equals ("Sing")) {
System.out.println ("Get 10,000 bucks!! ");
Return Method.invoke (Liming,args);
}else if (Methosname.equals ("Dance")) {
System.out.println ("Get 20,000 bucks!! ");
Return Method.invoke (liming, args);
}else{
System.out.println ("Li Ming does not support this feature!! ");
}
return null;
}
});
}
}

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.

Cglib Dynamic Agent
The dynamic agent mechanism of JDK can only implement the class of the interface, and the class that cannot implement the interface cannot implement the dynamic proxy of the JDK, the cglib is to implement the proxy for the class, his principle is to generate a subclass for the target class, and overwrite the method implementation enhancement, but because inherit is adopted, Therefore, the final decorated class cannot be proxied.
Example

1, Bookfacadecglib.java

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

2, Bookcadeimpl1.java

    1. PACKAGE&NBSP;NET.BATTIER.DAO.IMPL;&NBSP;&NBSP;
    2.   
    3. /** 
    4.  *   This is an implementation class   that does not implement an interface;
    5.  *  
    6.  *  @author  student 
    7.  *  
    8.  */  
    9. public < span class= "keyword" >class bookfacadeimpl1 {  
    10.      public void addbook ()  {  
    11.         system.out.println (
    12.     }  
    13. }  


3, Bookfacadeproxy.java

  1. Package net.battier.proxy;
  2. Import Java.lang.reflect.Method;
  3. Import Net.sf.cglib.proxy.Enhancer;
  4. Import Net.sf.cglib.proxy.MethodInterceptor;
  5. Import Net.sf.cglib.proxy.MethodProxy;
  6. /**
  7. * Use Cglib dynamic agent
  8. *
  9. * @author Student
  10. *
  11. */
  12. Public class Bookfacadecglib implements Methodinterceptor {
  13. private Object target;
  14. /** 
  15. * Create proxy object
  16. *
  17. * @param target
  18. * @return
  19. */
  20. Public Object GetInstance (object target) {
  21. this.target = target;
  22. Enhancer enhancer = new enhancer ();
  23. Enhancer.setsuperclass (this.target.getClass ());
  24. //callback method
  25. Enhancer.setcallback (this);
  26. //Create proxy object
  27. return enhancer.create ();
  28. }
  29. @Override
  30. //callback method
  31. Public Object Intercept (Object obj, Method method, object[] args,
  32. Methodproxy proxy) throws Throwable {
  33. System.out.println ("things start");
  34. Proxy.invokesuper (obj, args);
  35. System.out.println ("End of Thing");
  36. return null;
  37. }
  38. }


4, Testcglib.java

    1. Package net.battier.test;
    2. Import NET.BATTIER.DAO.IMPL.BOOKFACADEIMPL1;
    3. Import Net.battier.proxy.BookFacadeCglib;
    4. Public class Testcglib {
    5. public static void Main (string[] args) {
    6. Bookfacadecglib cglib=New Bookfacadecglib ();
    7. BOOKFACADEIMPL1 bookcglib= (BOOKFACADEIMPL1) cglib.getinstance (new BookFacadeImpl1 ());
    8. Bookcglib.addbook ();
    9. }
    10. }

Java Dynamic Agent

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.