Dynamic agent of Java

Source: Internet
Author: User

Dynamic agent is one of Gof 23 design patterns, database connection and transaction management, the method interception of AOP in spring, and the mock objects used in unit test are all used in dynamic proxy.

The Java Dynamic Agent can be implemented by using the class java.lang.reflect.Proxy of the JDK.

Create a dynamic proxy by using the Proxy.newproxyinstance () method.

The Newproxyinstance () method has three parameters:
1, ClassLoader
2. Interfaces that require agents
3, the implementation of Invocationhandler interface

Invocationhandler handler = new Myinvocationhandler (); MyInterface proxy = (myinterface) proxy.newproxyinstance (                            MyInterface.class.getClassLoader (),                            new class[] { Myinterface.class},                            handler);

Let's take a look at the definition of the Invocationhandler interface

Public interface invocationhandler{  object Invoke (Object proxy, Method method, object[] args)         throws Throwable;}

All of the method calls to the dynamic proxy object proxy go to the implementation class of the Invocationhandler interface.

The Invocationhandler interface has only one invoke method, the proxy parameter in the Invoke method is the dynamic proxy object, and the method object is the methods in the proxy interface, and the args parameter is the method parameter.

Dynamic agent of 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.