The dynamic agent is the class that is generated when the program is executed dynamically, when it is generated to provide a set of interface to it, then the class declares the implementation of these interfaces, the generated proxy objects do not do any substantive work, such as adding other business logic, etc. A handler must be provided when the instance is built, which takes over the work, plus the application is the reflection technology.
Code:
Interfaces implemented by the proxy object of life
Public interface Subjectinf {string Say (string name);}
The specific implementation of the object being proxied:
public class Subjectimpl implements Subjectinf {@Overridepublic string Say (string name) {//TODO auto-generated method Stu Breturn "Hello" +name;}}
Implement a Handler
public class Subjectdyanmic implements Invocationhandler {private Subjectimpl subject;public subjectdyanmic ( Subjectimpl subject) {super (); this.subject = subject;} @Overridepublic object Invoke (Object proxy, Method method, object[] args) throws Throwable {System.out.println ("invoke Run ... "); if (args = = null) {Method.invoke (subject, args); return null;} else{ String res = (string) method.invoke (subject, args) ; return res;}}}
Test Client
public class Client {public static void main (string[] args) {Subjectimpl sub =new Subjectimpl (); Invocationhandler handler = new Subjectdyanmic (sub); System.out.println ("Pre-entry");//Generate proxy object Subjectinf Subinf = (subjectinf) proxy.newproxyinstance (Sub.getclass (). getClassLoader () , Sub.getclass (). Getinterfaces (), handler); SYSTEM.OUT.PRINTLN ("proxy generation Completed");/*** * The Invoke Method (reflection) in handler is executed immediately when a method of the Proxied object is executed. The handler method is not executed when a method of the Proxied object is not executed */ String Res=subinf. Say ("Li"); System.out.println (res);}}
</pre><pre>
Program output:
Pre-agent generation completed invoke Run...helloli
If we test that clinent does not invoke a method of the Proxied object, the output is:
Agent generation completed before entering Helloli
Visible dynamic agent is divided into two parts, one is the generation of proxy objects, and the other is based on the Java reflection to execute the proxy object of some methods, that is, invoke Invoke method.
Java Dynamic Agent