本系列文章均整理自我在先前一家公司的CGLib使用总结和笔记。分享出来,希望对看到的人有所帮助,同时欢迎大家提出宝贵意见。如需转载,请勿修改,且注明作者shensy及出处。
--------------------------------------
实战CGLib系列文章
本篇介绍接口生成器InterfaceMaker。
一、作用:
InterfaceMaker会动态生成一个接口,该接口包含指定类定义的所有方法。
二、示例:
比较简单,先定义一个类,仍使用本系列第一篇中的那个ConcreteClassNoInterface类,该类包含3个方法:
public class ConcreteClassNoInterface { public String getConcreteMethodA(String str){ System.out.println("ConcreteMethod A ... "+str); return str; } public int getConcreteMethodB(int n){ System.out.println("ConcreteMethod B ... "+n); return n+10; } public int getConcreteMethodFixedValue(int n){ System.out.println("getConcreteMethodFixedValue..."+n); return n+10; } }
用这个类内定义的方法来生成一个接口:
InterfaceMaker im=new InterfaceMaker(); im.add(ConcreteClassNoInterface.class); Class interfaceOjb=im.create(); System.out.println(interfaceOjb.isInterface());//true System.out.println(interfaceOjb.getName());//net.sf.cglib.empty.Object$$InterfaceMakerByCGLIB$$13e205f
interfaceOjb就是InterfaceMaker生成的接口,从接口名字可以看出。
看一下该接口内部的方法:
扫描二维码关注公众号,回复:
724781 查看本文章
Method[] methods = interfaceOjb.getMethods(); for(Method method:methods){ System.out.println(method.getName()); }
输出结果,与ConcreteClassNoInterface类内定义的方法完全相同:
getConcreteMethodA getConcreteMethodB getConcreteMethodFixedValue
下面通过生成的接口,可以对某个类进行Enhancer(本系列前面介绍过Enhancer,此处不再讲解)。
Object obj = Enhancer.create(Object.class, new Class[]{ interfaceOjb }, new MethodInterceptor() { public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { return "intercept!"; } }); Method method = obj.getClass().getMethod("getConcreteMethodA", new Class[]{String.class}); System.out.println(method.invoke(obj, new Object[]{"12345"}));此处让Object生成的代理类实现了由InterfaceMaker生成的接口,但是由于Object类并没有覆写其中的方法,因此,每当对生成接口内方法进行MethodInterceptor方法拦截时,都返回一个字符串,并在最后打印出来。
结束语:
以上就是CGLib接口生成器InterfaceMaker的一个示例,本系列下一篇将继续介绍CGLib的强大功能,敬请期待。