Java reflection of JDK dynamic proxy implementation simple Aop__java

Source: Internet
Author: User
Tags aop reflection

JDK Dynamic Proxy implements simple AOP

JDK dynamic proxies are an important feature of Java reflection. It provides a dynamic feature for Java in some way, which brings infinite space to the application. The famous Hessian, Spring AOP is based on dynamic proxy implementations. This article will briefly introduce the use of JDK dynamic proxies.

about agent Mode

Agent mode is a very common design pattern that is often used in our applications. The general scenario is that we have a ready-made class, its function is perfect, but there are some deficiencies, this time we need to expand some new features, but do not want to reinvent the wheel, this time you can use the proxy class to replace the original target class, through the combination of patterns, Add a few extra features to the target class.

The class diagram of the proxy mode is generally as follows:

Figure 1: Proxy mode class structure diagram

Figure 2: Proxy mode sequence diagram

JDK Dynamic Proxy

The so-called JDK dynamic proxy is the process of dynamically generating a red proxy class at run time. and static agent is not the same place is static agent at compile time to complete the implementation of proxy class. So how is the dynamic proxy implemented?

According to the example below, take a step-by-step look.

Suppose there is such an interface Speak:

Package proxy; Public interface Speak {public void SayHello ();}

Implement class Peoplespeak.

Package proxy; public class Personspeak implements Speak {public void SayHello () {System.out.println ("Hello");}

When we go to call Personspeak's SayHello, it's obviously output hello. Now we need to generate Speak proxy classes dynamically at runtime through dynamic proxies, and make some output before and after calling the SayHello method. Complete functions similar to AOP.

Based on the above ideas, we need to have a Personspeak proxy class, it holds the Personspeak object, so it can be very convenient to complete the task. If the implementation of static proxy is obviously very simple, then how to implement with dynamic proxy.

This time we can use the Proxy class in the Java reflection. This class is the core class for JDK dynamic proxies. The Proxy class has a feature that dynamically creates a class at run time. Dynamic to create a Speak subclass, while the subclass holds an instance of the Personspeak class, the function of which is to implement the first part of the proxy class.

About Java reflection method, Field, class, Construtor, etc. here do not introduce, focusing on proxy and Invocationhandler class.

Introduction to Proxy and Invocationhandler classes

The Proxy class provides a very important way to dynamically generate the implementation classes for several interfaces. The specific implementation process is implemented by the Proxygenerator class, which is a class that is relatively low-level, and is not described here too much. At the same time, the dynamic class needs to hold a subclass object that implements the Invocationhandler interface. The subclass object of the Invocationhandler interface is another layer of proxy for our target class. For each method implementation within the interface, it is invoked by invoking the reflection of the subclass object of the Invocationhandler interface. This means that the dynamic proxy class is actually a proxy for the Invocationhandler subclass object. Then the Invocationhandler subclass object is sometimes the proxy of our target class. Through this layer of agent we can achieve the above functions. This sentence may not be very well understood, but it is really the way to achieve, perhaps through the following diagram to better understand:

Figure 3:JDK Dynamic Proxy call Process

As can be seen from the image above, the JDK dynamic reflection is not a simple layer of proxies, but rather a method of invoking the target object through the layer-layer proxy, ultimately through the reflection of methods, while the implementation of AOP can be placed in the Invocationhandler implementation class.

So based on the above introduction to dynamic proxies, there are two things you need to do to implement Personspeak AOP

1. Implement a Invocationhandler subclass that holds the Speak object, change the subclass to invoke the Personspeak method by Mechod reflection, and implement the AOP function before and after calling the method.

2. The implementation of a dynamic Speak subclass of the proxy class factory, change factory can dynamically create Speak subclass.

Specifically implemented as follows:

1. Speakinvocationhandler (implement Invocationhandler interface)

You can see that the Invoke method of this class is key to AOP, all of which are invoked by invoke, within invoke, to invoke target object target by reflection, and to implement AOP before and after the call.

Package proxy; Import Java.lang.reflect.InvocationHandler; Import Java.lang.reflect.Method; public class Speakinvocationhandler implements Invocationhandler {public Object target; Speakinvocationhandler (object target) {this.target = target;} public object Invoke (object proxy, Method method, object[] args) throws Throwable {System.out.println (Method.getname () + "invoked!"); Object result = Method.invoke (target, args); System.out.println (Method.getname () + "return!"); return result; } }

2. Proxyfactory

Package proxy; Import Java.lang.reflect.InvocationHandler; Import Java.lang.reflect.Proxy; public class Proxyfactory {class CLS; Invocationhandler h; Public Proxyfactory (String className, Invocationhandler h) {try {cls = Class.forName (className); this.h = h;} catch (Cl Assnotfoundexception e) {e.printstacktrace ();}} Public Object Createproxyobject () {return proxy.newproxyinstance (Cls.getclassloader (), Cls.getinterfaces (), h);}

Proxyfactory mainly through the reflection of the proxy class to create the interface of the subclass, and the subclass is a Invocationhandler agent, all the method implementation, is through the Invocationhandler proxy to invoke.

Finally, look at the Main function:

Package proxy; Import Java.lang.reflect.InvocationHandler; public class Proxytest {public static void main (String args[]) {Speak s = new Personspeak (); Invocationhandler h = new Speakinvocationhandler (s); Proxyfactory proxyfactory = new Proxyfactory (PersonSpeak.class.getName (), h); Speak speakproxy = (Speak) proxyfactory.createproxyobject (); Speakproxy.sayhello (); } }

The resulting output is as follows:

SayHello invoked!

Hello

SayHello return!

From the output, we can see that the red output part is the result of our dynamic proxy implementation. The process of the dynamic agent is accomplished through the process as above.

In addition to implementing AOP, dynamic proxies can also be used to implement remote service proxies. For example, Hessian is to invoke a remote service by dynamically creating a remote service proxy class, thus making the application transparent to the remote service. The Hessian call process is as follows:

Figure 4:hessian Remote Service invocation procedure

Summary

The JDK dynamic Proxy is a very important feature of Java reflection, and the JDK dynamic proxy class can also be used as a remote service proxy class for SOAP, which in a way provides a dynamic feature of Java and provides a lot of flexibility for applications.

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.