Dynamic Agent for Java

Source: Internet
Author: User
Tags throwable

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.