Dynamic agent for JDK Public InterfaceSubject {Object request (); voidhello ();} Public classRealsubjectImplementssubject{ PublicRealsubject () {}; PublicObject request () {System.out.println ("Realsubject"); return1; } Public voidHello () {System.out.println ("Hello"); }} Public classProxysubjectImplementsInvocationhandler {PrivateObject obj; Publicproxysubject (Object obj) { This. obj =obj; } Publicobject Invoke (Object proxy, Method method, object[] args)throwsthrowable {System.out.println ("Pre-enhanced"); //Object m = method.invoke (obj, args);method.invoke (obj, args); System.out.println ("After enhanced"); //return m; return NULL; }} Public classTest { Public Static voidMain (string[] args) {Proxysubject proxy=NewProxysubject (Newrealsubject ()); Subject Sub=(Subject) proxy.newproxyinstance (realsubject.class. getClassLoader (), Realsubject.class. Getinterfaces (), proxy); Sub.request (); Sub.hello (); Dynamic agent for}}cglib Public classHelloWorld { Public voidSayHelloWorld () {System.out.println ("Helloworld!"); } Public intsay () {System.out.println (11111111); return1; }} Public classCglibproxyImplementsMethodinterceptor {PrivateObject obj; Publicobject Createproxy (object target) { This. obj =Target; Enhancer Enhancer=Newenhancer (); Enhancer.setsuperclass ( This. Obj.getclass ()); Enhancer.setcallback ( This); Enhancer.setclassloader (Target.getclass (). getClassLoader ()); returnenhancer.create (); } PublicObject Intercept (object proxy, method, object[] params, methodproxy methodproxy)throwsthrowable {System.out.println ("Pre-enhanced"); Object result=methodproxy.invokesuper (proxy, params); System.out.println ("After enhanced"); return NULL; }} Public classTest { Public Static voidMain (string[] args) {HelloWorld Hello=NewHelloWorld (); Cglibproxy Cglibproxy=NewCglibproxy (); HelloWorld HW=(HelloWorld) cglibproxy.createproxy (hello); Hw.sayhelloworld (); Hw.say (); }}
Dynamic Agent for Java