JDK动态代理和CGLib有什么区别? [英] What is the difference between JDK dynamic proxy and CGLib?

查看:1019
本文介绍了JDK动态代理和CGLib有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果是代理设计模式 JDK的动态代理和第三方动态代码生成API,例如CGLib

In case of the Proxy Design Pattern, What is the difference between JDK's Dynamic Proxy and third party dynamic code generation API s such as CGLib?

使用这两种方法之间的区别是什么时候应该优先选择另一种?

What is the difference between using both the approaches and when should one prefer one over another?

推荐答案

JDK动态代理只能通过接口代理(因此您的目标类需要实现一个接口,然后由代理类实现)。

JDK Dynamic proxy can only proxy by interface (so your target class needs to implement an interface, which is then also implemented by the proxy class).

CGLIB(和javassist)可以通过子类创建代理。在这种情况下,代理成为目标类的子类。不需要接口。

CGLIB (and javassist) can create a proxy by subclassing. In this scenario the proxy becomes a subclass of the target class. No need for interfaces.

所以Java动态代理可以代理:公共类Foo实现iFoo CGLIB可以代理的地方: 公共课Foo

So Java Dynamic proxies can proxy: public class Foo implements iFoo where CGLIB can proxy: public class Foo

编辑:

我应该提到因为javassist和CGLIB通过子类化使用代理,这就是你在使用依赖于它的框架时不能声明最终方法或使类最终的原因。这将阻止这些库允许子类化并覆盖您的方法。

I should mention that because javassist and CGLIB use proxy by subclassing, that this is the reason you cannot declare final methods or make the class final when using frameworks that rely on this. That would stop these libraries from allowing to subclass your class and override your methods.

这篇关于JDK动态代理和CGLib有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆