Parse instances in dynamic proxy mode in detail:
1. First, create an interface (there are real methods to be implemented ):
PublicinterfaceSubject {
PublicvoidRequest (); // method to be implemented
}
2. Write a real theme class to implement the subject interface (and implement the method ):
PublicclassRealsubject
ImplementsSubject {
PublicvoidRequest () {// method in the implementation Interface
System.Out. Println ("implementation method of real theme ");
}
}
3. Write a dynamic proxy class to implement the invocationhandler interface:
// The dynamic proxy class should implement the invocationhandler interface (under the java. Lang. Reflect package)
PublicclassProxyhandle
Implements
Invocationhandler {
Object OBJ =
Null;
// Write a binding method and bind different interfaces for proxy
PublicObject BIND (Object OBJ ){
This. OBJ = OBJ;
// The return value of this method is an object.
// Proxy has a method newproxyinstace (); there are three parameters: First: The Class Loader that represents the real class instance of the proxy
// The second parameter indicates the interface implemented by the real class to be proxy
// The third is the proxy class itself.
ReturnProxy.Newproxyinstance(Obj. getclass (). getclassloader (), obj. getclass (). getinterfaces (),
This);
}
// Invocationhandler interface method invoke ()
// The method in invoke () indicates the method in the implementation interface of the real class.
PublicObject
Invoke (Object proxy, method, object [] ARGs)
ThrowsThrowable {
// Call the invoke () method in the parameter method, which has two parameters
// The first parameter indicates the real class of the proxy.
// The second parameter indicates the input parameter object array.
System.Out. Println ("proxy previous task ~~~ ");
Object o = method. Invoke (This. OBJ, argS );
System.Out. Println ("task after proxy ~~ ");
ReturnO; // return the implementation class of a proxy Interface
}
}
4. Test the dynamic proxy class: testproxy
Public class testproxy {
Public static void main (string ARGs []) {
Proxyhandle pH = new proxyhandle (); // get the proxy class Object
// Real subject object bound to the proxy
Subject sub = (subject) Ph. BIND (New realsubject (); // bind the real subject to the proxy
Sub. Request (); // call the request of a real object (a method in the implementation Interface)
// At this time, the invock () method in the proxy class will be automatically called to complete the proxy process
}
// If the proxy has different real classes, directly change the parameters in the BIND () method, and pass in the real class you want to proxy to OK.
// This enables dynamic proxy.
}
In this way, a dynamic proxy instance is completed in four steps, and each step is explained in the code.