1. Define the interface
1 Package cc.whoisit; 2 3 Public Interface ispeak {4 Public void speak (); 5 }
2. Implement the interface
1 Packagecc.whoisit;2 3 Public classEnglishspeakImplementsispeak{4 5 @Override6 Public voidspeak () {7 //TODO auto-generated Method Stub8System.out.println ("I speak 中文版.");9 }Ten}
3, Write Handler
1 Packagecc.whoisit;2 3 ImportJava.lang.reflect.InvocationHandler;4 ImportJava.lang.reflect.Method;5 6 Public classSpeakhandlerImplementsInvocationhandler {7 PrivateObject obj;8 9 Publicspeakhandler (Object obj) {Ten Super(); One This. obj=obj; A } - - @Override the Publicobject Invoke (Object proxy, Method method, object[] args) - throwsThrowable { - //TODO auto-generated Method Stub - This. before (); +Object result = Method.invoke ( This. obj, args); - This. After (); + returnresult; A } at - Private voidbefore () { -System.out.println ("before.")); - } - - Private voidAfter () { inSystem.out.println ("After."); - } to}
This handler is where we control the behavior of the Proxied object.
4. Agent Factory
1 Packagecc.whoisit;2 3 ImportJava.lang.reflect.Proxy;4 5 Public classProxyfactory {6 Public Static<T>t newinstance (t obj) {7Speakhandler handler =NewSpeakhandler (obj);8T proxy =(T) proxy.newproxyinstance (Obj.getclass (). getClassLoader (), Obj.getclass (). Getinterfaces (), handler);9 returnproxy;Ten } One}
5. Testing
1 Packagecc.whoisit;2 3 Public classTest {4 5 Public Static voidMain (string[] args) {6 //TODO auto-generated Method Stub7Ispeak proxy = Proxyfactory.newinstance (Newenglishspeak ());8 proxy.speak ();9 }Ten}
The purpose of writing this dynamic agent is to write the database connection automatically shut down to prepare. The database connection is automatically closed, which is actually the close () method of calling the data connection in after in Hanlder. In this way, the agent is concerned about the database to do curd operation, do not care about the database connection closed.
Java Dynamic Agent