The difference between JDK dynamic agent and Cglib dynamic agent

Source: Internet
Author: User

JDK Dynamic Agent

    1. A class that can only be proxied to implement an interface

    2. A class that does not implement an interface cannot implement a dynamic proxy for the JDK

Cglib Dynamic Agent

    1. For the class to implement the proxy

    2. Produces a subclass of the specified target class, intercepting all calls to the parent class method through the method volley technique

Implementing dynamic proxies with Cglib

Package Com.imooc.cglib;public class Train {public void Move () {System.out.println ("train in Transit");}}
import java.lang.reflect.method;import net.sf.cglib.proxy.enhancer;import  net.sf.cglib.proxy.methodinterceptor;import net.sf.cglib.proxy.methodproxy;public class  cglibproxy implements methodinterceptor {  private enhancer enhancer =  new enhancer ();   public object getproxy (class clazz) {  // Set class   enhancer.setsuperclass (Clazz) for creating subclasses,   enhancer.setcallback (this);     return enhancer.create (); }  /*  *  intercepts calls to all target class methods   * obj : Instance of the target class   * m: Reflection Object   * args: Method parameter   * proxy: instance of the proxy class   *    *  (non-javadoc)   *  @see  net.sf.cglib.proxy.methodinterceptor# Intercept (java.lang.object, java.lang.reflect.method, java.lang.object[],  Net.sf.cglib.proxy.MethodProxy)   */  @Override  PUBLIC&NBSp;object intercept (object obj, method m, object[] args,    Methodproxy proxy)  throws Throwable {  // TODO Auto-generated  Method stub    system.out.println ("log Start"); Method of calling parent class by   //proxy class    Proxy.invokesuper (Obj, args);   system.out.println ("Log End");   return null; }
Package Com.imooc.cglib;public class Client {public static void main (string[] args) {Cglibproxy proxy = new Cglibproxy (  );  Train t = (Train) proxy.getproxy (Train.class); T.move (); }}

The difference between JDK dynamic agent and Cglib dynamic agent

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.