What is agent and dynamic agent?
1. To buy a train ticket to the life of a case description.
Because every day to adjust the bug so I do not have time to train tickets, and then to the train ticket agents to call tickets, and then agents to the railway station to buy me a ticket. So understand, need me to do things, agents help me to do, but need to make a fee.
Don't talk nonsense, just go to Java code!
Java Dynamic Agent
Interface (abstract things to buy tickets)
Public interface Icalc {
public int Add (int i, int j);
}
Implement this interface (specific to the things I buy tickets)
public class Calcimpl implements Icalc {
@Override
public int Add (int i,int j) {
int result = i + j;
return result;
}
}
Dynamically create proxy objects (agents have the ability to buy tickets, as long as I call on it)
Import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Method;
Import Java.lang.reflect.Proxy;
Import java.util.ArrayList;
Import Java.util.Arrays;
public class Calcloggingproxy implements Invocationhandler {
The object being proxied
Private Icalc target;
Public Calcloggingproxy () {}
Public calcloggingproxy (Icalc obj) {
target = obj;
}
@Override
public object invoke (object proxy, Method method, object[] args) throws Throwable {
String methodName = Method.getname ();
Log
System.out.println ("Invoke...before--->" +methodname+ "---" +arrays.aslist (args));
Execution method
Object result = Method.invoke (Target,args);
Log
System.out.println ("invoke...after---->" +result);
return result;
}
public static Object Factory1 (Icalc target)
{
Gets the class of the object being proxied
Class cls = Target.getclass ();
Which class loader is responsible for the proxy object
ClassLoader loader = Cls.getclassloader ();
The type of the proxy object, that is, which methods
Class [] interfaces = new Class[]{icalc.class};
Executes the code when the method of the proxy object is called---> assigns a value to the proxy object---> Automatically invokes invoke ();
Invocationhandler handler = new Calcloggingproxy (target);
Returns an instance of a proxy object
Return proxy.newproxyinstance (Loader,interfaces,handler);
}
}
Test (I just made a phone call to book a ticket)
public class Proxytest {
public static void Main (string[] args) {
Icalc target = new Calcimpl ();
Icalc calcproxy = (icalc) calcloggingproxy.factory1 (target);
int result = Calcproxy.add (2, 4);
SYSTEM.OUT.PRINTLN (result);
}
}
Test the effect (then you have the ticket)
Invoke...before---> Add---[2, 4]
Invoke...after---->6
6
Simple test of agent and dynamic Proxy in Java