A deep understanding of the Java proxy mechanism

Source: Internet
Author: User

Dynamic proxy is actually Java. lang. reflect. the proxy class dynamically generates a Class byte based on all the interfaces you specified. This class inherits the proxy class and implements all the interfaces you specified (the interface array you passed in the parameters ); then, use the specified classloader to load the Class byte into the system, generate such a class object, and initialize some values of the object, such as invocationhandler, it is the method member corresponding to all interfaces. After initialization, the object is returned to the called client. In this way, the client obtains a proxy object that implements all your interfaces. See instance analysis:

Business Interface

public interface BusinessProcessor { public void processBusiness();}

Business implementation

Public class businessprocessorimpl implements businessprocessor {

Public void processbusiness (){

System. Out. println ("processing business .....");

}

}

Three Business proxies

Import java. Lang. Reflect. invocationhandler;

Import java. Lang. Reflect. method;

Public class businessprocessorhandler implements invocationhandler {

Private object target = NULL;

 

Businessprocessorhandler (object target ){

This.tar get = target;

}

 

Public object invoke (Object proxy, method, object [] ARGs)

Throws throwable {

System. Out. println ("you can do something here before process your business ");

Object result = method. Invoke (target, argS );

System. Out. println ("you can do something here after process your business ");

Return result;

}

}

4. Client Applications

Import java. Lang. Reflect. field;

Import java. Lang. Reflect. method;

Import java. Lang. Reflect. modifier;

Import java. Lang. Reflect. proxy;

Public class test {

Public static void main (string [] ARGs ){

Businessprocessorimpl bpimpl = new businessprocessorimpl ();

Businessprocessorhandler handler = new businessprocessorhandler (bpimpl );

Businessprocessor BP = (businessprocessor) proxy. newproxyinstance (bpimpl. getclass (). getclassloader (), bpimpl. getclass (). getinterfaces (), Handler );

BP. processbusiness ();

}

}

Now let's take a look at the printed results:

You can do something here before process your business

Processing business .....

You can do something here after process your business

Through the results, we can easily see the role of proxy, which can do some auxiliary work you want to do before and after your core business methods, such as log logs and security mechanisms.

 

Now let's analyze the working principle of the above class.

Class one or two. Let's take a look at Category 3. The invocationhandler interface's invoke method is implemented. In fact, this class is the final fixed interface method called by the proxy. Proxy no matter how the client's business method is implemented. When the client calls proxy, it only

Will call the invocationhandler's invoke interface, so our real implementation method must be called in the invoke method. The link is as follows:

Businessprocessorimpl bpimpl = new businessprocessorimpl ();

Businessprocessorhandler handler = new businessprocessorhandler (bpimpl );

Businessprocessor BP = (businessprocessor) proxy. newproxyinstance (....);

BP. processbusiness () --> invocationhandler. Invoke () --> bpimpl. processbusiness ();

So what is BP like. Let's change the main method to see it:

Public static void main (string [] ARGs ){

Businessprocessorimpl bpimpl = new businessprocessorimpl ();

Businessprocessorhandler handler = new businessprocessorhandler (bpimpl );

Businessprocessor BP = (businessprocessor) proxy. newproxyinstance (bpimpl. getclass (). getclassloader (), bpimpl. getclass (). getinterfaces (), Handler );

BP. processbusiness ();

System. Out. println (BP. getclass (). getname ());

}

Output result:

You can do something here before process your business

Processing business .....

You can do something here after process your business
$ Proxy0

BP was originally an object of the $ proxy0 class. So what does this class look like? Okay. Let's write another two methods to print out this class and see what the three heads and six arms are? We will write the following two static methods under main.

Public static string getmodifier (INT modifier ){

String result = "";

Switch (modifier ){

Case modifier. Private:

Result = "private ";

Case modifier. Public:

Result = "public ";

Case modifier. protected:

Result = "protected ";

Case modifier. Abstract:

Result = "abstract ";

Case modifier. Final:

Result = "final ";

Case modifier. Native:

Result = "native ";

Case modifier. Static:

Result = "static ";

Case modifier. Synchronized:

Result = "synchronized ";

Case modifier. Strict:

Result = "strict ";

Case modifier. Transient:

Result = "transient ";

Case modifier. Volatile:

Result = "volatile ";

Case modifier. interface:

Result = "interface ";

}

Return result;

}

 

Public static void printclassdefinition (class clz ){



String clzmodifier = getmodifier (clz. getmodifiers ());

If (clzmodifier! = NULL &&! Clzmodifier. Equals ("")){

Clzmodifier = clzmodifier + "";

}

String superclz = clz. getsuperclass (). getname ();

If (superclz! = NULL &&! Superclz. Equals ("")){

Superclz = "extends" + superclz;

}



Class [] interfaces = clz. getinterfaces ();



String inters = "";

For (INT I = 0; I <interfaces. length; I ++ ){

If (I = 0 ){

Inters + = "implements ";

}

Inters + = interfaces [I]. getname ();

}



System. Out. println (clzmodifier + clz. getname () + "" + superclz + "" + inters );

System. Out. println ("{");



Field [] fields = clz. getdeclaredfields ();

For (INT I = 0; I <fields. length; I ++ ){

String modifier = getmodifier (fields [I]. getmodifiers ());

If (modifier! = NULL &&! Modifier. Equals ("")){

Modifier = Modifier + "";

}

String fieldname = Fields [I]. getname ();

String fieldtype = Fields [I]. GetType (). getname ();

System. Out. println ("" + Modifier + fieldtype + "" + fieldname + ";");

}



System. Out. println ();



Method [] Methods = clz. getdeclaredmethods ();

For (INT I = 0; I <methods. length; I ++ ){

Method method = methods [I];

String modifier = getmodifier (method. getmodifiers ());

If (modifier! = NULL &&! Modifier. Equals ("")){

Modifier = Modifier + "";

}



String methodname = method. getname ();



Class returnclz = method. getreturntype ();

String retruntype = returnclz. getname ();



Class [] clzs = method. getparametertypes ();

String paralist = "(";

For (Int J = 0; j <clzs. length; j ++ ){

Paralist + = clzs [J]. getname ();

If (J! = Clzs. Length-1 ){

Paralist + = ",";

}

}

Paralist + = ")";



Clzs = method. getexceptiontypes ();

String Exceptions = "";

For (Int J = 0; j <clzs. length; j ++ ){

If (j = 0 ){

Exceptions + = "throws ";

}

Exceptions + = clzs [J]. getname ();



If (J! = Clzs. Length-1 ){

Exceptions + = ",";

}

}



Exceptions + = ";";



String methodprototype = Modifier + retruntype + "" + methodname + paralist + exceptions;



System. Out. println ("" + methodprototype );



}

System. Out. println ("}");

}

 

Rewrite the main method.

Public static void main (string [] ARGs ){

Businessprocessorimpl bpimpl = new businessprocessorimpl ();

Businessprocessorhandler handler = new businessprocessorhandler (bpimpl );

Businessprocessor BP = (businessprocessor) proxy. newproxyinstance (bpimpl. getclass (). getclassloader (), bpimpl. getclass (). getinterfaces (), Handler );

BP. processbusiness ();

System. Out. println (BP. getclass (). getname ());

Class clz = bp. getclass ();

Printclassdefinition (clz );

}

Now let's look at the output:

You can do something here before process your business

Processing business .....

You can do something here after process your business
$ Proxy0

$ Proxy0 extends java. Lang. Reflect. Proxy implements com. Tom. Proxy. Dynamic. businessprocessor

{

Java. Lang. Reflect. Method M4;

Java. Lang. Reflect. Method m2;

Java. Lang. Reflect. Method M0;

Java. Lang. Reflect. Method m3;

Java. Lang. Reflect. Method M1;

Void processbusiness ();

Int hashcode ();

Boolean equals (Java. Lang. Object );

Java. Lang. String tostring ();

}

Obviously, the proxy. newproxyinstance method will do the following:

1. A class is dynamically generated based on the second input parameter interfaces to implement the interface in interfaces. In this example, the processbusiness method of the businessprocessor interface is used. It inherits the proxy class and overwrites three methods, including hashcode, tostring, and equals. For specific implementation, see proxygenerator. generateproxyclass (...). In this example, the $ proxy0 class is generated.

2. Load the newly generated class to JVM using the first input parameter classloder. About $ proxy0 class load

3. Call the $ proxy0 (invocationhandler) constructor of $ proxy0 to create the $ proxy0 object, and use the interfaces parameter to traverse all its interface methods, and generate several method member variables of the method object initialization object.

4. Return the $ proxy0 instance to the client.

Now. Let's see how the client is tuned.

1. The client obtains the $ proxy0 instance object. Since $ proxy0 inherits businessprocessor, it is no problem to convert it to businessprocessor.

Businessprocessor BP = (businessprocessor) proxy. newproxyinstance (....);

2, BP. processbusiness ();

Actually, $ proxy0.processbusiness () is called. Then, the implementation of $ proxy0.processbusiness () is to call the invoke method through invocationhandler!

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.