具体类的动态代理 [英] Dynamic proxy for concrete classes

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

问题描述

我想在Java程序中定义一个方法拦截器,换句话说我希望在每次方法调用时都执行一个行为。
此应用程序不在应用程序服务器中执行,因此我不能在调用拦截器时使用EJB。
我找到了一个不错的标准Java库中的代理 API,但它有限,因为它需要代理创建中的接口:

I want to define a method interceptor in a Java program in other words I want to have a behaviour which is executed at each method call. This application isn't executed in an application server and therefore I can't use the EJB around invoke interceptors. I have found a nice Proxy API in the standard Java libraries but its limited because it needs an interface in the proxy creation:

 Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
                                      new Class[] { Foo.class },
                                      handler);

是否有类似的API不强制将Foo.class声明为接口?

Is there a similar API which doesn't force Foo.class to be declared as an interface?

推荐答案

为什么不使用 CGLIB ?有关详细信息,请参阅本文

Why not use CGLIB ? See this article for more information.


如果要代理没有接口的旧类,该怎么办?
您可以使用CGLIB。 CGLIB是一个功能强大的高性能代码
生成库。在封面下,它使用ASM,一个小但快速的
字节码操作框架,将现有字节代码转换为
生成新类。 CGLIB比JDK动态代理
方法更快。本质上,它动态生成一个子类来覆盖
代理类的非final方法,并连接
回调给用户定义的拦截器的钩子。

What if you want to proxy legacy classes that do not have interfaces? You can use CGLIB. CGLIB is a powerful, high-performance code generation library. Under the cover, it uses ASM, a small but fast bytecode manipulation framework, to transform existing byte code to generate new classes. CGLIB is faster than the JDK dynamic proxy approach. Essentially, it dynamically generates a subclass to override the non-final methods of the proxied class and wires up hooks that call back to the user-defined interceptors.

这篇关于具体类的动态代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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