实战CGLib系列文章
本篇介绍接口生成器InterfaceMaker。
一、作用:
InterfaceMaker会动态生成一个接口,该接口包含指定类定义的所有方法。
二、示例:
比较简单,先定义一个类,仍使用本系列第一篇中的那个ConcreteClassNoInterface类,该类包含3个方法:
Java代码
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;
}
}
用这个类内定义的方法来生成一个接口:
Java代码
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生成的接口,从接口名字可以看出。
看一下该接口内部的方法:
Java代码
Method[] methods = interfaceOjb.getMethods();
for(Method method:methods){
System.out.println(method.getName());
}
输出结果,与ConcreteClassNoInterface类内定义的方法完全相同:
控制台代码
getConcreteMethodA
getConcreteMethodB
getConcreteMethodFixedValue
下面通过生成的接口,可以对某个类进行Enhancer(本系列前面介绍过Enhancer,此处不再讲解)。
Java代码
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方法拦截时,都返回一个字符串,并在最后打印出来。