Dynamic proxy for concrete classes

我是研究僧i 提交于 2019-11-30 08:39:14

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

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.

Unfortunately there is no such API for classes. Many frameworks are using bytecode generation libraries like CGLIB to achieve this.

You can try one of the mocking classes. The simplest approach may be to sub-class, your class. Or you could use AOP to inject the logging code you want.

sun.misc.ProxyGenerator can be used to generate proxy classes and doesn't check that their "interfaces" are all interfaces. Its generateClassFile method gives you the bytecode as a byte array, which you can save to link into future builds or alter with third-party tools.

Note that if any of the "interfaces" has a final method, you'll get an error when you try to load the class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!