java jdk动态代理 cglib动态代理demo
最近在研究java动态代理这块,以前也看了很多次java动态代理,感觉一直不是怎么明白,这两天看了看又明白了些,现给出我参考网上写的一个demo
jdk动态代理实现:
View Code
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class DynamicProxy implements InvocationHandler { private Target target; public DynamicProxy(Target target) { this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("before the work"); method.invoke(target, args); System.out.println("after the work"); return null; } public Target getProxy() { Class<?>[] interfaces = this.target.getClass().getInterfaces(); if (interfaces == null || interfaces.length == 0) { interfaces = new Class<?>[] { Target.class }; } Target proxy = (Target) Proxy.newProxyInstance(this.target.getClass() .getClassLoader(), interfaces, this); return proxy; } public static void main(String[] args) { Target target = new TargetImpl(); new DynamicProxy(target).getProxy().sayHello(); } } interface Target { public void sayHello(); } class TargetImpl implements Target { public void sayHello() { System.out.println("hello world"); } }
cglib动态代理demo:
View Code
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 TestCglibProxy { public static void main(String[] args) { Target target = new Target(); TestCglibProxy testCglibProxy = new TestCglibProxy(); Target targetProxy = (Target) testCglibProxy.createProxy(target .getClass()); targetProxy.sayHello(); } public Object createProxy(Class targetClass) { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(targetClass); enhancer.setCallback(new MethodInteceptor()); return enhancer.create(); } } class MethodInteceptor implements MethodInterceptor { @Override public Object intercept(Object object, Method method, Object[] arg2, MethodProxy methodProxy) throws Throwable { System.out.println("start to do the work"); Object result = methodProxy.invokeSuper(object, arg2); System.out.println("end:do the work"); return "haha"; } } class Target { public void sayHello() { System.out.println("hello world"); } }
jdk实现版本只支持接口的动态代理,如果某个类没有实现接口,他就无法为他进行动态代理,在生成代理对象的时候需要传入的参数就包括“接口”
cglib实现方式不利用接口,而是为现有的类,生成一个子类,然后进行调用.cglib底层实现用asm方式
对于这两种方式的底层具体实现还需要再研究