Java JDK Dynamic Agent detailed _java

Source: Internet
Author: User

The JDK dynamic proxy is to proxy a class, the proxy class must implement at least one interface, and only the methods in the interface can be represented.

JDK implementation of dynamic Proxy is generally divided into three steps:

1. writing interfaces and implementing classes.

2. Write a processor that implements the Invocationhandler interface, which has only one method, and its signature is public object invoke (object proxy, methods method, object[] Args
Throws Throwable can be dynamically intercepted by adding its own code before and after the method call in the implementation method of the processor. Note that proxy is the generated dynamic proxy class, and it is not really the class that we are represented in, so you can add a member variable of type object to the processor, pointing to the class that we really require to be represented (that is, the implementation class in step 1th).

3. generate dynamic proxy classes using the Newproxyinstance method of the Java.lang.reflect.Proxy class. All calls to proxy methods are direct calls to the generated dynamic proxy class, but they are forced to convert to the interface of the method we are calling.

JDK Principle Analysis:
By analyzing the source code of the proxy, you can see the detailed generation of the dynamic proxy class. The Newproxyinstance method first generates a class instance of the dynamic proxy class, and then calls its constructor with the parameter type Invocationhandler to generate the dynamic proxy class and return.

How does a class instance of a dynamic proxy class generate the class byte stream of a dynamic proxy class by Proxygenerator classes to load it into the method area.

The process of parsing a class byte stream can be seen using the proxy as its parent, implementing all the methods of the interface to be proxied, and the main implementation of each method is to invoke the processor's Invoke method.

The main code for the build process of the class byte stream is as follows:

Copy Code code as follows:



Private byte[] Generateclassfile ()


{


Addproxymethod (Hashcodemethod, java/lang/object);


Addproxymethod (Equalsmethod, java/lang/object);


Addproxymethod (Tostringmethod, java/lang/object);


for (int i = 0; i < interfaces.length; i++)


{


Method amethod[] = Interfaces[i].getmethods ();


for (int k = 0; k < amethod.length; k++)


Addproxymethod (Amethod[k], interfaces[i]);

}

List List;
for (Iterator iterator = Proxymethods.values (). iterator (); Iterator.hasnext (); Checkreturntypes (list)
List = (list) iterator.next ();

Try


{


Methods.add (Generateconstructor ());


for (Iterator Iterator1 = Proxymethods.values (). iterator (); Iterator1.hasnext ();)


{


List List1 = (list) iterator1.next ();


Iterator Iterator2 = List1.iterator ();


while (Iterator2.hasnext ())


{


Proxymethod Proxymethod = (proxymethod) iterator2.next ();


Fields.Add (New FieldInfo (Proxymethod.methodfieldname, "Ljava/lang/reflect/method;", 10));


Methods.add (<span style= "color:red" >proxymethod.generatemethod () </span><span style= "COLOR: #000000 ">);</span>





Copy Code code as follows:



}


}





Methods.add (Generatestaticinitializer ());


}


catch (IOException IOException)


{


throw new Internalerror ("Unexpected I/O Exception");


}


if (Methods.size () > 65535)


throw new IllegalArgumentException ("Method limit Exceeded");


if (Fields.size () > 65535)


throw new IllegalArgumentException ("Field limit exceeded");


Cp.getclass (Dottoslash (className));


Cp.getclass ("Java/lang/reflect/proxy");


for (int j = 0; J < Interfaces.length; J + +)


Cp.getclass (Dottoslash (Interfaces[j].getname ()));





Cp.setreadonly ();


Bytearrayoutputstream Bytearrayoutputstream = new Bytearrayoutputstream ();


DataOutputStream DataOutputStream = new DataOutputStream (bytearrayoutputstream);


Try


{


Dataoutputstream.writeint (-889275714);


Dataoutputstream.writeshort (0);


Dataoutputstream.writeshort (49);


Cp.write (DataOutputStream);


Dataoutputstream.writeshort (49);


Dataoutputstream.writeshort (Cp.getclass (Dottoslash (ClassName)));


Dataoutputstream.writeshort (Cp.getclass ("Java/lang/reflect/proxy"));


Dataoutputstream.writeshort (interfaces.length);


for (int l = 0; l < interfaces.length; l++)


Dataoutputstream.writeshort (Cp.getclass (Dottoslash (Interfaces[l].getname ()));





Dataoutputstream.writeshort (Fields.size ());


FieldInfo FieldInfo;





Copy Code code as follows:



Add properties


for (Iterator Iterator3 = Fields.iterator (); Iterator3.hasnext (); Fieldinfo.write (DataOutputStream))

FieldInfo = (FieldInfo) iterator3.next ();
Add method
Dataoutputstream.writeshort (Methods.size ());
MethodInfo MethodInfo;
for (Iterator Iterator4 = Methods.iterator (); Iterator4.hasnext (); Methodinfo.write (DataOutputStream))
MethodInfo = (MethodInfo) iterator4.next ();

Dataoutputstream.writeshort (0);
}
catch (IOException Ioexception1)
{
throw new Internalerror ("Unexpected I/O Exception");
}
return Bytearrayoutputstream.tobytearray ();
}




Note:Add red part of code Proxymethod.generatemethod ()The method body is generated for each method, and by looking at the source you can see that the Invoke method of implementing the processor in the Invocationhandler interface is invoked.

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.