Java Dynamic Agent

Source: Internet
Author: User

The dynamic proxy provided by Java is an implementation of the "proxy mode". Introduction to Proxy mode: http://www.cnblogs.com/endlu/p/5169749.html

Static proxies have some drawbacks, writing a proxy class for each of the proxy classes can make the system bloated and inflexible. Dynamic proxies are dynamically generated at run time by a proxy class and proxy object.    Solve the problem in this area. The so-called dynamic agent, in the courtyard can be understood. The proxy class of static proxy is written well beforehand, the compiler compiles into bytecode, and then it is loaded and used by the class loader.    While the dynamic agent is at runtime, the program generates binary bytecode according to bytecode rules, and then the class loader loads. proxy class, since acting as a proxy, he should at least provide and be the same as the proxy class method, so that the client as transparent as possible to use the specific functions. There are two ways to limit this consistency in Java:
    • Inherit the same interface: the scenario used by the JDK
    • proxy class Integration proxy class: Cglib scheme
JDKThe dynamic proxy class provided by the JDK is located under the Java.lang.reflect package and consists of two classes:
    • public interface Invocationhandler. It only defines a method Object:invoke (Object Obj,method method, object[] args). In use, we need to provide an implementation of this interface, the Invoke method can write our agent to implement the function. The first argument is the proxy class, the second is the method called, and the third is the argument list.
    • proxy class. The proxy class, which is created dynamically at run time. acts as a proxy for the object being proxied. It also consists of two static methods:
      • Class Getproxyclass (ClassLoader loader, class[] interfaces). The method can return a proxy class. Parameter one is the class loader, and parameter two is all the interfaces of the proxy class. The method generates the binary data of class and then loads it into a class by ClassLoader.
      • Object Newproxyinstance (ClassLoader loader, class[] Interfaces,invocationhandler h). The method returns a proxy class object. The third parameter is the above-mentioned handler, which implements the processing of the proxy class. Call the method above to generate a constructor for the class by reflection, instantiating an object.
Example:
public class End implements people{public void say (String s) {System.out.    println ("End is saying:" + s); }}public interface People {public void say (String s);}    public class Endinvokehandler implements Invocationhandler {private people p;    Public Endinvokehandler (People p) {THIS.P = P;  The public object invoke (object proxy, Method method, object[] args) throws Throwable {System.out.println ("before        End say, Gusse he'll say: "+ (String) args[0]);        Method.invoke (P, args);        System.out.println ("After end say");    return null;        }}public class Testdynamicproxy {public static void main (string[] args) {End end = new End ();        Endinvokehandler handler = new Endinvokehandler (end);        Class AClass = End.getclass ();        People people = (people) proxy.newproxyinstance (Aclass.getclassloader (), Aclass.getinterfaces (), handler);    People.say ("hahaha!"); }}

  

Output:

Before end say, Gusse He'll say:hahaha!end is Saying:hahaha!after end say

  

Disadvantage: The class being proxied needs to implement at least one interface, otherwise it will be out of the proxy. Cglib       As mentioned earlier, the JDK requires that the class being proxied needs to implement at least one interface, and another scenario for cglib: inheritance. The principle is not very different, see examples directly.
    
public class End {public    void say (String s) {        System.out.println ("End is saying:" + s);}    } public class Endinteceptor implements Methodinterceptor {    @Override public    object Intercept (object o, Method Method, object[] objects, Methodproxy methodproxy) throws Throwable {        System.out.println ("Before say, I guess he'll Say: "+ objects[0]);        Methodproxy.invokesuper (O, objects);        System.out.println ("After end say");        return null;}    } public class Testcglib {public    static void Main (string[] args) {        end end = new End ();        Endinteceptor inteceptor = new Endinteceptor ();        Enhancer enhancer = new enhancer ();        Enhancer.setsuperclass (End.getclass ());        Enhancer.setcallback (inteceptor);        End endproxy = (end) enhancer.create ();        Endproxy.say ("Hello");}    }

Output:

Before say, I guess he'll say:helloend is Saying:helloafter end say

Where Methodinterceptor is the same function as the Invocationhandler in the JDK. When invoking the proxy method inside, note that the method proxies the Methodproxy Invokesuper method.

Because Cglib is based on inheritance, there are also limitations: it cannot be the final class, nor can the final method be proxied.

Java Dynamic Agent

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.