cglib动态代理
通过前面介绍的文章可知,JDK的动态代理用起来非常简单,但动态代理中使用动态代理的对象必须实现一个或多个接口。如果一个类没有实现任何接口,只是一个纯粹的类,如果要实现对它的代理,那该该怎么办?为例解决这个问题,因此就引入了cglib动态代理。
为了保证关于代理的这几篇文章连续性,本文先占个坑,只简单介绍如何使用cglib,以后会修改并深入研究下原理。
使用cglib之前首先要引入:
net.sf.cglib.proxy 相关的包
本文使用maven引入了cglib 2.2.2版本:
<!-- https://mvnrepository.com/artifact/cglib/cglib --> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2.2</version> </dependency>
例子如下:
代理类:
package cjj.proxy.cglib; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; import java.lang.reflect.Method; /** * Created by youaijj on 2018/5/12. */ public class HelloWorldCglib implements MethodInterceptor { private Object target; public Object getInstance(Object target){ this.target = target; Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(this.target.getClass()); enhancer.setCallback(this); Object proxy = enhancer.create(); return proxy; } public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { System.out.println("Before invocation"); methodProxy.invokeSuper(o, objects); System.out.println("After invocation"); return null; } }
真实类:
package cjj.proxy.cglib; /** * Created by youaijj on 2018/5/12. */ public class HelloWorldImpl { public void sayHello(String name) { System.out.println("Hello " + name); } }
测试:
package cjj.proxy.cglib; import net.sf.cglib.core.DefaultGeneratorStrategy; /** * Created by youaijj on 2018/5/12. */ public class MainTest { public static void main(String[] args) { HelloWorldCglib cglib = new HelloWorldCglib(); HelloWorldImpl proxy = (HelloWorldImpl)cglib.getInstance(new HelloWorldImpl()); proxy.sayHello("cjj"); try { createProxyClassFile(); } catch (Exception e) { e.printStackTrace(); } } // TODO: 2018/5/12 查找生成的代理类文件能实现 private static void createProxyClassFile() throws Exception { DefaultGeneratorStrategy strategy = new DefaultGeneratorStrategy(); //HelloWorldCglib cglib = new HelloWorldCglib(); //Enhancer enhancer = new Enhancer(); //enhancer.setSuperclass(new HelloWorldImpl().getClass()); //enhancer.setCallback(cglib); //byte[] data = strategy.generate(enhancer); } }
结果:
原理之后分析,未完待续。。。