问题描述
springboot项目中使用动态代理来调用方法
// 动态代理;cls是一个类;Strategy是一个接口
Strategy strategy = (Strategy) Proxy.newProxyInstance(cls.getClass().getClassLoader(), cls.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object Proxy, Method method, Object[] args) throws Throwable {
// 增强的逻辑代码...
return method.invoke(cls.getClass(), args);
}
})
原因分析
Proxy.newProxyInstance()生成的代理对象无法强转为Strategy。
网上说是因为被代理的类没有继承接口,而是继承了一个基类。但本例中确实是接口。
JDK动态代理的原理是根据定义好的规则,用传入的接口创建一个新类,这就是为什么采用动态代理时为什么只能用接口引用指向代理,而不能用传入的类引用执行动态类(摘自网络)。
解决方法
打印(或断点查看)cls.getClass().getClassLoader() 和cls.getClass().getInterfaces() 对象内容
Class<?> interfaces = cls.getClass().getInterfaces();
发现,interfaces对象中根本没有实现的Strateg接口对象。通过打印(或断点查看)cls.getInterfaces()对象
Class<?> interfaces = cls.getInterfaces();
发现,存在Strategy接口。
其他(ClassLoader、invoke方法第一个参数)根据情况作出修改。
故总结为:动态代理没有找到要代理的接口,此时要确认代理的接口是否"存在",从而传入正确的参数。
参考文章
primary:https://blog.csdn.net/qq_38409944/article/details/80296354
secondary:https://www.cnblogs.com/zhuochangjing/p/4975055.html
secondary:https://blog.csdn.net/kuaisuzhuceh/article/details/44756333
secondary:https://www.jianshu.com/p/9bcac608c714