Dynamic proxy cglib instance

Source: Internet
Author: User

1. Delegate class;

Package dynamic proxy 2; // This class needs to be enhanced public class userservice {public void create () {system. out. println ("create user");} public void Update () {system. out. println ("update user ");}}

2. proxy class implementation

1 package dynamic proxy 2; 2 3 Import Java. lang. reflect. method; 4 5 import net. SF. cglib. proxy. enhancer; 6 Import net. SF. cglib. proxy. methodinterceptor; 7 Import net. SF. cglib. proxy. methodproxy; 8 9 public class proxycglib implements methodinterceptor {10 // determine whether the operation permission is granted based on the input name. 11 private enhancer = new enhancer (); 12 13 private string name = NULL; 14 15 public proxycglib (string name) 16 {17 this. name = Name; 18 19} 20 // obtain the proxy class object. The input parameter is the delegate Class 21 public object getproxy (class clazz) {22 // set the Class 23 enhancer to create the subclass. setsuperclass (clazz); 24 enhancer. setcallback (this); 25 // use bytecode technology to dynamically create a subclass instance 26 return enhancer. create (); 27} 28 29 30 31 public object intercept (Object arg0, method arg1, object [] arg2, 32 methodproxy arg3) throws throwable {33 // todo auto-generated method stub34 35 if (! Name. equals ("Han") 36 {37 system. out. println (""); 38} 39 else40 {41 arg3.invokesuper (arg0, arg2); 42 43} 44 45 return NULL; 46} 47 48 49}

3. Client: Test

Package dynamic proxy 2; // Ref: The http://songbo-mail-126-com.iteye.com/blog/968792public class test {public static void main (string [] ARGs) {// todo auto-generated method stub // create a proxy object for user Zhang San/* proxycglib proxy = new proxycglib ("Zhang San"); userservice user = (userservice) proxy. getproxy (userservice. class); User. create (); */proxycglib proxy2 = new proxycglib ("Han"); userservice user2 = (userservice) proxy2.getproxy (userservice. class); user2.create ();}}

 

Dynamic proxy cglib instance

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.