Agent
Two concepts should be clarified first
Proxy object: An object that intercepts access to the target object
target object: The object to actually access
role of the agent
can be used to strengthen the method;
Dynamic Agent Demo
Target object public class target implements itarget{@Overridepublic void Test1 () {System.out.println ("test1 ()" of the target object);}}
//Proxy Object Public classProxyDemo1 {@Test Public voidtest1 () {//To create a dynamic proxy object FinalTarget tar=NewTarget ();//the anonymous inner class is called, and the final decorationITarget newproxyinstance = (itarget) proxy.newproxyinstance (Tar.getclass (). getClassLoader (),//passing a class loader that is consistent with the targetTar.getclass (). Getinterfaces (),//pass a class<?>[] interfaces NewInvocationhandler () {//implementing an interface using an anonymous inner class Invocationhandler@Override Publicobject Invoke (Object proxy, Method method, object[] args)throwsthrowable {System.out.println ("Logic before calling the target method"); Object Invoke=Method.invoke (tar, args); System.out.println ("Logic before calling the target method"); returninvoke; } } ); Newproxyinstance.test1 ();//Invoke is actually called under Invocationhandler }}
Execution results
Test1 () of the logical target object before the call to the target method invokes the logic before the target method
Note : The proxy mode of the JDK implementation of the dynamic proxy target object must have an interface, no interface can not implement the JDK
Version of the dynamic agent.
Concise use of agents in Java