JDK 和 CGLib 动态代理获取代理对象为 Null 的原因是什么?
IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天给大家整理了《JDK 和 CGLib 动态代理获取代理对象为 Null 的原因是什么?》,聊聊,我们一起来看看吧!
jdk 动态代理获取代理对象为 null 的问题
jdk 动态代理通过 proxy.newproxyinstance 生成代理对象,需要满足一定的条件,即目标类的接口必须实现自某个接口(一般是 java.lang.reflect.invocationhandler),并且该接口中的方法全部被 null 覆盖。
在你的代码中,invocationhandler 中的方法都被 null 覆盖了,但这导致了一个问题:无法从代理对象中调用实际的目标方法。要解决这个问题,需要在 invocationhandler 中覆盖 invoke 方法,并调用目标方法。
修改后的 invocationhandler:
invocationhandler h = new invocationhandler() { @override public object invoke(object proxy, method method, object[] args) throws throwable { return method.invoke(target, args); } };
cglib 动态代理获取代理对象为 null 的问题
cglib 动态代理不需要目标类实现接口,而是直接继承目标类的字节码,然后重写目标类中的方法。
在你的代码中,methodinterceptor 中的方法全部被 null 覆盖了,这与 jdk 动态代理中 invocationhandler 中的方法全部被 null 覆盖类似,会导致无法从代理对象中调用实际的目标方法。
要解决这个问题,需要在 methodinterceptor 中覆盖 intercept 方法,并调用目标方法。
修改后的 methodinterceptor:
MethodInterceptor methodInterceptor = new MethodInterceptor() { @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { return method.invoke(target, args); } };
今天关于《JDK 和 CGLib 动态代理获取代理对象为 Null 的原因是什么?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!