dynamic Agents in the Java reflection mechanism
dynamic proxy mode and its use
Step 1: Define an interface
//interface
Interface subject{
void action ();
}
Step 2: Define an implementation class for an interface, that is, the proxy class//By proxy class
Class Realsubject implements Subject {
@Override
public void action () {
System.out.println ("I am a proxy class, please execute Me");
}
}
Step 3: Define an implementation class that implements the Invocationhandler interface, which is the proxy classDynamic proxy Classes
Class Myinvocationhandler implements Invocationhandler {
Object obj;//Declaration of objects that implement an interface's proxy class
/*
* The role of the Blind () method:
* First, to instantiate the object being proxied (that is, to assign value)
* Second, return the object of a proxy class
*
* The three parameters of the Newproxyinstance () method function:
* First parameter: Class loader of the class being proxied
* Second parameter: The interface of the proxy class
* Third parameter: Class object that implements the Invocationhandler interface
*/
public object Blind (object obj) {
This.obj = obj;
Return Proxy.newproxyinstance (Obj.getclass (). getClassLoader (), Obj.getclass (). Getinterfaces (), this);
}
/*
* When a call to an overridden method is initiated through an object of the proxy class, it is converted to a call to the following invoke () method
*/
@Override
public object invoke (object proxy, Method method, object[] args)
Throws Throwable {
The return value of the Returnval:method () method
Object returnval = Method.invoke (obj, args);
return returnval;
}
}
complete the above 3 steps, you can directly create a main () method to implement the above dynamic agent, this is very simple, the code is as follows:
public class Testdynamicproxy {
public static void Main (string[] args) {
1. Create an object of a proxied class
Realsubject real = new Realsubject ();
2. Create an object with a class that implements the Invocationhandler interface
Myinvocationhandler handler = new Myinvocationhandler ();
3. Call the Blind () method and dynamically return a proxy class object that also implements the interface of the real class.
Object obj = Handler.blind (real);
Subject sub = (Subject) obj;//at this point the sub is the object of the proxy class
4. The proxy class object calls the action () method
Sub.action ();//Go to the Call of the Invoke () method on the implementation class of the Invocationhandler interface
}
}
Dynamic agent is so simple, hope to help you.
Dynamic agents in the Java reflection mechanism