Implement Dynamic proxy in the jar package of cglib

Source: Internet
Author: User

Import cglib-nodep-2.1_3.jar


Package com. jxnu. cglib; public class Person {public void m1 () {System. out. println ("method 1 executed");} public void m2 () {System. out. println ("method 2 executed ");}}


Package com. jxnu. cglib; import java. lang. reflect. method; import net. sf. cglib. proxy. callback; import net. sf. cglib. proxy. enhancer; import net. sf. cglib. proxy. methodInterceptor; import net. sf. cglib. proxy. methodProxy; public class PersonDemo {public static void main (String [] args) {final Person p = new Person (); // return the dynamic proxy object of p: this proxy object is a subclass of Person. Person pp = (Person) Enhancer. create (p. getClass (), new MethodInterceptor () {@ Overridepublic Object intercept (Object proxy, Method method, Object [] arg2, MethodProxy arg3) throws Throwable {long time = System. nanoTime (); // nanosecond 1 millisecond = 1000 nanosecond Object obj = method. invoke (p, arg2); System. out. println (method. getName () + "running time:" + (System. nanoTime ()-time) + "nanosecond"); return obj ;}}); pp. m1 (); pp. m2 ();}}

It intercepts all methods of the person class. It is a dynamic method that is uncertain.

Output result:

Method 1 is executed
M1 running time: 262234 nanoseconds
Method 2 is executed
M2 running time: 49461 nanoseconds


Zookeeper

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.