博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
实战CGLib系列之proxy篇(五):接口生成器InterfaceMaker
阅读量:6951 次
发布时间:2019-06-27

本文共 1723 字,大约阅读时间需要 5 分钟。

  hot3.png

实战CGLib系列文章

本篇介绍接口生成器InterfaceMaker。

一、作用:

InterfaceMaker会动态生成一个接口,该接口包含指定类定义的所有方法。

二、示例:

比较简单,先定义一个类,仍使用本系列第一篇中的那个ConcreteClassNoInterface类,该类包含3个方法:

Java代码  

  1. public class ConcreteClassNoInterface {  

  2.     public String getConcreteMethodA(String str){  

  3.         System.out.println("ConcreteMethod A ... "+str);  

  4.         return str;  

  5.     }  

  6.     public int getConcreteMethodB(int n){  

  7.         System.out.println("ConcreteMethod B ... "+n);  

  8.         return n+10;  

  9.     }  

  10.     public int getConcreteMethodFixedValue(int n){  

  11.         System.out.println("getConcreteMethodFixedValue..."+n);  

  12.         return n+10;  

  13.     }  

  14. }  

用这个类内定义的方法来生成一个接口:

Java代码  

  1. InterfaceMaker im=new InterfaceMaker();  

  2. im.add(ConcreteClassNoInterface.class);  

  3. Class interfaceOjb=im.create();  

  4. System.out.println(interfaceOjb.isInterface());//true  

  5. System.out.println(interfaceOjb.getName());//net.sf.cglib.empty.Object$$InterfaceMakerByCGLIB$$13e205f  

interfaceOjb就是InterfaceMaker生成的接口,从接口名字可以看出。

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

Java代码  

  1. Method[] methods = interfaceOjb.getMethods();  

  2. for(Method method:methods){  

  3.     System.out.println(method.getName());  

  4. }  

输出结果,与ConcreteClassNoInterface类内定义的方法完全相同:

控制台代码  

  1. getConcreteMethodA  

  2. getConcreteMethodB  

  3. getConcreteMethodFixedValue  

下面通过生成的接口,可以对某个类进行Enhancer(本系列前面介绍过Enhancer,此处不再讲解)。

Java代码  

  1. Object obj = Enhancer.create(Object.classnew Class[]{ interfaceOjb },   

  2. new MethodInterceptor() {  

  3.    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {  

  4.       return "intercept!";  

  5.    }  

  6. });  

  7.   

  8. Method method = obj.getClass().getMethod("getConcreteMethodA"new Class[]{String.class});  

  9. System.out.println(method.invoke(obj, new Object[]{

    "12345"}));  

此处让Object生成的代理类实现了由InterfaceMaker生成的接口,但是由于Object类并没有覆写其中的方法,因此,每当对生成接口内方法进行MethodInterceptor方法拦截时,都返回一个字符串,并在最后打印出来。

转载于:https://my.oschina.net/mn1127/blog/649018

你可能感兴趣的文章
【益智题】十块钱去哪了?
查看>>
静态密码已经"OUT" 探索身份验证新方式
查看>>
轻松搞定RabbitMQ(四)——发布/订阅
查看>>
projecteuler_problem12
查看>>
VN2VN——中小企业的网络融合之道
查看>>
数百亿的新疆安防市场,集成巨头告诉你如何才能从中分杯羹
查看>>
[译] REST API 已死,GraphQL 长存
查看>>
学点PYTHON基础的东东--数据结构,算法,设计模式---访问者模式
查看>>
独家 | 陆化普:大数据、AI解决交通管理难题的新思路
查看>>
你需要的不是大数据 而是正确的数据~
查看>>
我只能说,Spring Data REST真的很燥辣
查看>>
使用短生命周期容器(Ephemeral Containers)构建微服务化的工作流
查看>>
R语言领跑 大数据岗位霸占IT薪酬榜单
查看>>
靠播放业务吃不饱?音乐流媒体纷纷“加电商”卖周边
查看>>
SSL之父称SSL不会因被攻击而失去生命力
查看>>
解读对象存储九大关键特征
查看>>
重构计算力 浪潮M5新一代服务器闪耀登场
查看>>
品高云产品经理邱洋:做国内云计算第一品牌
查看>>
大数据挑战:敢不敢不要加入人的判断?
查看>>
2014中国高校SAS数据分析大赛拉开帷幕
查看>>