CGLib之Enhancer
2016-06-15 00:03
375 查看
Enhancer允许为非接口类型创建一个Java代理。Enhancer动态创建了给定类型的子类但是拦截了所有的方法。和
来个场景模拟一下AOP
ProxyFactory用于创建增强代理实现了方法拦截
运行结果:
接下来我们了解下Enhancer可以使用的Callback接口。
接口都很简单。
先来一个基础POJO类:
使用
唯一需要注意的就是proxy.invokeSuper和proxy.invoke的区别。invokeSuper是退出当前interceptor的处理,进入下一个callback处理,invoke则会继续回调该方法,如果传递给invoke的obj参数出错容易造成递归调用。
相比于Dispatcher,lazyLoader在第一次获取了loadObject后,会进行缓存,后续的请求调用都会直接调用该缓存的属性。
这个是有道理的,如果你的对象是昂贵的在其创建,不知道对象什么时候被使用。请注意,一些增强的类的构造函数必须被代理对象和延迟加载的对象。因此,确保还有另一个廉价的(可能保护)构造函数获得或使用一个接口类型的代理。你可以选择提供参数的调用Enhancer#create(Object...)。
再者说一些构造函数必须被代理和生成的对象调用。
Proxy不一样的是,不管是接口还是类他都能正常工作。
来个场景模拟一下AOP
package cglib.enhancer; public class Hello { public String sayHello(boolean throwException) throws Exception { System.out.println("hello everyone!"); if(throwException) throw new Exception("test exception"); return "123"; } }
ProxyFactory用于创建增强代理实现了方法拦截
package cglib.enhancer; 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 ProxyFactory implements MethodInterceptor { //要代理的原始对象 private Object obj; public Object createProxy(Object target) { this.obj = target; Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(this.obj.getClass());// 设置代理目标 enhancer.setCallback(this);// 设置回调 enhancer.setClassLoader(target.getClass().getClassLoader()); return enhancer.create(); } @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { Object result = null; try { // 前置通知 before(); result = proxy.invokeSuper(obj, args); // 后置通知 after(); } catch (Exception e) { exception(); }finally{ beforeReturning(); } return result; } private void before() { System.out.println("before method invoke"); } private void after() { System.out.println("after method invoke"); } private void exception() { System.out.println("method invoke exception"); } private void beforeReturning() { System.out.println("before returning"); } }场景类:
package cglib.enhancer; public class EnhancerTest { public static void main(String[] args) throws Exception { Hello hello = new Hello(); ProxyFactory cglibProxy = new ProxyFactory(); Hello proxy = (Hello) cglibProxy.createProxy(hello); String result=proxy.sayHello(true); System.out.println(result); } }
运行结果:
before method invoke hello everyone! method invoke exception before returning null当然把true改为false之后结果变为:
before method invoke hello everyone! after method invoke before returning 123
接下来我们了解下Enhancer可以使用的Callback接口。
package net.sf.cglib.proxy; /** * All callback interfaces used by {@link Enhancer} extend this interface. * @see MethodInterceptor * @see NoOp * @see LazyLoader * @see Dispatcher * @see InvocationHandler * @see FixedValue */ public interface Callback { }Callback接口是一个空接口,没有任何契约方法,它只表示这是一个回调。接下来看它的子接口:
接口都很简单。
先来一个基础POJO类:
public class SampleClass { public String test(String input) { return "Hello world!"; } }
FixedValue
使用FixedValue可以很容易的替换掉方法的返回值。
@Test public void testFixedValue() throws Exception { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(SampleClass.class); enhancer.setCallback(new FixedValue() { @Override public Object loadObject() throws Exception { return "Hello cglib!"; } }); SampleClass proxy = (SampleClass) enhancer.create(); assertEquals("Hello cglib!", proxy.test(null)); }在上面的例子中,enhancer返回一个
SampleClass的子类实例,当所有的方法被调用的时候返回匿名FixedValue回调返回的值。当然了如果方法返回的不是String类型例如,hashcode()将抛出一个类型转换异常,因为"Hello cglib!"不能转换为java.lang.Number类型。
InvocationHandler
@Test public void testInvocationHandler() throws Exception { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(SampleClass.class); enhancer.setCallback(new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if(method.getDeclaringClass() != Object.class && method.getReturnType() == String.class) { return "Hello cglib!"; } else { throw new RuntimeException("Do not know what to do."); } } }); SampleClass proxy = (SampleClass) enhancer.create(); assertEquals("Hello cglib!", proxy.test(null)); assertNotEquals("Hello cglib!", proxy.toString()); }这个回调允许你去回答调用的方法。但是你要小心使用这个回调,因为这个代理对象的所有的方法调用都会使用InvocationHandler#invoke方法,这样的话可能导致死循环。为了避免这种情况你可以使用MethodInterceptor。
MethodInterceptor
@Test public void testMethodInterceptor() throws Exception { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(SampleClass.class); enhancer.setCallback(new MethodInterceptor() { @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { if(method.getDeclaringClass() != Object.class && method.getReturnType() == String.class) { return "Hello cglib!"; } else { return proxy.invokeSuper(obj, args); } } }); SampleClass proxy = (SampleClass) enhancer.create(); assertEquals("Hello cglib!", proxy.test(null)); assertNotEquals("Hello cglib!", proxy.toString()); proxy.hashCode(); // Does not throw an exception or result in an endless loop. }
唯一需要注意的就是proxy.invokeSuper和proxy.invoke的区别。invokeSuper是退出当前interceptor的处理,进入下一个callback处理,invoke则会继续回调该方法,如果传递给invoke的obj参数出错容易造成递归调用。
LazyLoader
尽管LazyLoader唯一的方法和FixedValue的一模一样,但是他们还是有一个根本上的区别。相比于Dispatcher,lazyLoader在第一次获取了loadObject后,会进行缓存,后续的请求调用都会直接调用该缓存的属性。
这个是有道理的,如果你的对象是昂贵的在其创建,不知道对象什么时候被使用。请注意,一些增强的类的构造函数必须被代理对象和延迟加载的对象。因此,确保还有另一个廉价的(可能保护)构造函数获得或使用一个接口类型的代理。你可以选择提供参数的调用Enhancer#create(Object...)。
Dispatcher
Dispatcher和LazyLoader很想但是每次调用方法的时候不会存储加载的对象。这允许改变一个类的实现但不改变原来的对象。
再者说一些构造函数必须被代理和生成的对象调用。
ProxyRefDispatcher
这个类携带了代理对象的引用,通过它的签名调用。例如这允许委托方法调用代理的另一个方法。要清楚这很容易造成死循环,并且总是导致死循环如果同样的方法被ProxyRefDispatcher#loadObject(Object)调用。NoOp
像名字所说的一样,这个类不做任何操作。相反地,它委托每个方法的调用给被增强类的方法实现。相关文章推荐
- 地图应用开发(android)使用百度地图sdk详解+案例附源码
- Runtime 的个人总结
- kafka初识
- 为数据库引擎访问配置 Windows 防火墙
- HL8548-G
- linux sonar安装
- flume1.6 install
- kafka 安装 单机测试
- 在CentOS 7 中安装htop
- 初识 Freemarker 自动生成代码
- DevOps,不是一个传说!
- BarTender 中英文界面的操作详解
- 常用数据结构
- 外贸企业如何选择域名服务器租用网络时代IDC问答
- 怎样用ZBrush快速雕刻皮肤纹理
- 设计模式之策略模式
- KLite V2正式发布
- KLite API参考手册
- 架构模式与设计模式
- 400电话业务功能