实战CGLib系列之proxy篇(五):接口生成器InterfaceMaker

本系列文章均整理自我在先前一家公司的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生成的接口,从接口名字可以看出。

看一下该接口内部的方法:

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的强大功能,敬请期待。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值