JDK Dynamic Agent
A class that can only be proxied to implement an interface
A class that does not implement an interface cannot implement a dynamic proxy for the JDK
Cglib Dynamic Agent
For the class to implement the proxy
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