我想在 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/