当前位置:网站首页>使用代理对象执行实现类目标方法异常
使用代理对象执行实现类目标方法异常
2022-08-04 22:47:00 【DanceDonkey】
使用JDK方式创建动态代理对象时,通常都是会强转为目标接口类型。
public class Test {
public static void main(String[] args) throws Exception{
BaseController baseController = new BaseControllerImpl();
InvocationHandler handler = new MyInvocationHandler(baseController);
BaseController target = (BaseController) Proxy.newProxyInstance(BaseController.class.getClassLoader(), new Class[]{
BaseController.class}, handler);
target.a4("111");
}
}
此时的target就是一个代理对象,同时是Proxy与BaseController的实例,此时以接口的形式来调用方法调用的时接口的方法是可以的,什么意思? 可参考如下代码
public static void main(String[] args)throws Exception {
Method a4 = BaseController.class.getMethod("a4", String.class);
Method a4Impl = BaseControllerImpl.class.getMethod("a4", String.class);
BaseControllerImpl baseController = new BaseControllerImpl();
a4Impl.invoke(baseController,"111");
a4.invoke(baseController,"222");
}
BaseController是接口,BaseControllerImpl 是实现类,获取了接口的a4方法和实现类型的a4方法,然后创建了BaseController的一个实现类,用实现类去分别反射调用这两个method,发现调用成功了。
但是如果是使用创建的代理对象去执行实现类的方法则会抛出异常。
public static void main(String[] args) throws Exception{
BaseController baseController = new BaseControllerImpl();
InvocationHandler handler = new MyInvocationHandler(baseController);
BaseController target = (BaseController) Proxy.newProxyInstance(BaseController.class.getClassLoader(), new Class[]{
BaseController.class}, handler);
Method a4 = BaseController.class.getMethod("a4", String.class);
Method a4Impl = BaseControllerImpl.class.getMethod("a4", String.class);
a4.invoke(target,"111");
a4Impl.invoke(target,"222");
}
这个其实也可以很好想明白target是一个代理对象,是BaseController的代理对象,本身和BaseControllerImpl是没有关系的,他俩都实现了BaseController接口,因此可以说是兄弟关系,但是兄弟之间就不能实现相同方法的调用了,必须得是父类或自身得方法可以。所以在JDK实现的代理中,在调用接口目标方法时,是调用的接口的方法。
可通过debug查看在代理对象调用方法时的method签名,可以很明显看到是接口中的方法签名。对于Spring中声明的切面来说,切面类并不能生成代理对象,只不过是通知Spring根据切面配置的pointcut来检测bean是否需要创建代理对象,用哪种方式创建等,而切面类声明的方法只是用来告诉Spring是哪种通知类型。
边栏推荐
- CS8416国产替代DP8416 数字音频接收器
- 备战9月,美团50道软件测试经典面试题及答案汇总
- 3D建模师为了让甲方爸爸过稿,还可以这么做,就是在赚血汗钱啊
- DREAMWEAVER8 部分问题解决方案
- Leaflets of three bouquet of roses
- 【项目实战】仿照Room实现简单管理系统
- [Mock Interview - 10 Years of Work] Are more projects an advantage?
- panic: reflect: reflect.Value.SetString using value obtained using unexported field
- shell选择结构(if)
- Nacos配置中心之客户端长轮询
猜你喜欢
随机推荐
How to right use of WebSocket in project
3D激光SLAM:LeGO-LOAM---两步优化的帧间里程计及代码分析
深度学习 RNN架构解析
力扣19-删除链表的倒数第 N 个结点——链表
【C - 基本概念】
Acwing3593. 统计单词
被领导拒绝涨薪申请,跳槽后怒涨9.5K,这是我的心路历程
golang打开文件和读写文件
PHP(3)
备战9月,美团50道软件测试经典面试题及答案汇总
js中小数四则运算精度问题原因及解决办法
软测人面试 ,HR 会问到哪些问题?学会涨薪3000+
VC bmp文件总结
轮播图动态渲染
MySQL的JSON 数据类型2
关于el-table列表渲染
Leaflets of three bouquet of roses
亿流量大考(3):不加机器,如何抗住每天百亿级高并发流量?
ANT1.7下载以及配置方法
Latex快速插入作者ORCID