Dynamic proxies in Java

Source: Internet
Author: User

I think to understand the dynamic agent, the first to understand the static agent, because the dynamic agent is to solve the static problem appears, see the previous static agent summary, directly see the diagram

It can be seen that the implementation of the agent is the three-party class, so in order to solve the disadvantages of static agents, need to run the dynamic generation of proxy classes.

In Java, the JDK provides a proxy class to create dynamic classes that are defined in the JDK

Foo f = (foo) proxy.newproxyinstance (Foo.class.getClassLoader (),                                          new class<?>[] {foo.class},                                          handler);

First explain the three parameters, the first parameter is the class loader of the proxy class, the second parameter is the instance of the proxy class, the most important is the third parameter, is a Invocationhandler object, the final method we want to call is to pass this handler object,

This handle object has only the Invoke method

invoke(Object proxy, 方法 method, Object[] args)

Processes the method call on the proxy instance and returns the result. This is the JDK on the explanation, plainly, we want to do business logic is written here, this invoke also has three parameters, in fact, I think the proxy class in the face of these three parameters explained quite clearly,
  • A method call on a proxy instance through one of its proxy interfaces will be dispatched to an instance of the invoke method that invokes the handler, the proxy instance, java.lang.reflect.Method the object of the called method, java.lang.reflect.Method and an array of type object containing the arguments Object . The calling handler handles the encoding method call appropriately, and the returned result is returned as a result of the method's invocation on the proxy instance.

    The first parameter proxy is our dynamic creation of proxy object, is the first sentence above, proxy instance! The second parameter is the byte-code object of the target method, which is the array of methods of the proxy method, if you do not understand what is the bytecode or the ClassLoader, you are just like the method array, and the last parameter represents the parameter when the target method is called. Return is the return of the method that called the proxy object to return it.

    /** Interface **/ Public InterfaceTargetinterface { Public voidmethod1 ();  PublicString method2 ();  Public intMETHOD3 (intx);}/** by proxy class **/ Public classTargetImplementstargetinterface{@Override Public voidmethod1 () {System.out.println ("Method1 running ..."); } @Override PublicString method2 () {System.out.println ("Method2 running ..."); return"Method2"; } @Override Public intMETHOD3 (intx) {returnx; }}/** Test Dynamic Agent **/ Public classproxytest {@Test Public voidtest1 () {//Get dynamic Proxy objects----Create a virtual proxy object for target dynamically in memory at run time//Objproxy is a proxy object that determines who the proxy object is based on the parametersTargetinterface Objproxy =(Targetinterface) proxy.newproxyinstance (Target.class. getClassLoader (),//the same class loader as the target object                NewClass[]{targetinterface.class},                 NewInvocationhandler () {//invoke represents the method that executes the proxy object@Override//method: Methods Bytecode object representing the target object//args: Parameters for methods that represent the response of the target object                     PublicObject Invoke (Object proxy, Method method, object[] args)throwsthrowable {System.out.println ("Logic before the target method"); //methods for executing target objectsObject invoke = Method.invoke (NewTarget (), args); System.out.println ("Logic after the target method"); returninvoke;                }                }            );        Objproxy.method1 (); String method2=objproxy.method2 ();            System.out.println (METHOD2); }    }

    There are a lot of things I have commented on, it is difficult to understand that this sentence may be

    Object invoke = Method.invoke (new Target (), args);

    This code if you understand the reflection, you should be able to see that this is actually a reflection, the first parameter is a proxy class instance, args is the method parameter, this sentence is actually called the proxy object method. Which means we can enhance the object in this invoke,

    Finally, I conclude that the dynamic agent base should use the principle of reflection, according to the interface of the class passed in the bytecode file (that is , the new class<?>[] {foo.class} parameter ), the dynamic creation of a proxy class, When we call the method of this proxy class (that is , objproxy.method1 (); )

    We actually call the Invoke method, which reflects the method used by the proxy class.

Dynamic proxies in Java

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.