java - 具体类的动态代理

标签 java reflection dynamic-proxy

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

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

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

最佳答案

为什么不使用 CGLIB ?参见 this article获取更多信息。

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.

关于java - 具体类的动态代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7878521/

相关文章:

java - LeetCode 上的二和 III 的复杂性

java - Kotlin 反射问题

c# - 是否可以通过 DynamicProxy 向类型添加属性?

java - 如何将文件读入以列表作为值的 HashMap ?

java - 为什么这个 if 语句总是返回 true?

用于解析 latex 或 MathML 字符串的 Java 或 Scala 库

c# - 通过反射获取控件

.net - 是否可以禁用 .NET 程序集的反射?

c# - 为什么 DynamicProxy 的拦截器不会为 *each* 虚拟方法调用调用?

java - XML 配置的 Java 配置模拟不起作用