如何实现 AOP 来更改 Java 界面内容?
我目前在我所在的一个项目中使用 Seasar2 Framework。该框架在日本非常流行,但我在查找英文文档时遇到问题。即使在他们的官方英文翻译网站上,他们也只是讨论该框架使用依赖注入和 AOP。
我对他们在 S2Dao 组件之一中使用它的方式很感兴趣。基本上,您只需要自动创建接口 DAO 类和框架,在运行时更改代码并创建在中间调用的中间类。因此,数据库事务代码会自动添加到该类中。我想知道,是否有任何关于如何完成此操作的分步解释? java可以在运行时更改代码并在运行时更改方法吗?
关于如何完成此操作有很好的参考吗?我只是想知道框架是如何做到这一点的。
I am current using Seasar2 Framework on a project that I am in. The framework is quite popular here in Japan but I am having problem in finding English documentations. Even on their official English translation site, they just discuss that the framework use Dependency Injection and AOP.
I was intrigued with the way they use it in one of their component S2Dao. Basically you only need to create interface DAO class and the framework automatically, changes the code on runtime and creates intermediate class that get called in the middle. Hence DB transactions codes are automatically added to the class. I was wondering, is there any step by step explanation on how this is done? Can java change code on runtime and change the method on runtime?
Are good reference on how this is done? I just want to know how the framework is doing this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,可以在运行时动态实现接口,也可以操作编译后的字节码。
Java 提供了一种内置机制来在运行时实现接口,称为 动态代理类。
还有一些不错的库,例如 cglib 或 javassist,它不仅允许您实现接口,还可以扩展类并在运行时操作字节码(以更改行为的一个方法,例如)。像 Spring 和 Hibernate 这样的框架使用这些库来发挥其魔力,因此您的框架也可能正在使用其中的一些库。
注意:如果您好奇,这些库可以“调整”字节码,因为它们不使用 JVM 的默认 ClassLoader,而是使用自己的 ClassLoader 加载您的类,因此它们可以完全控制所加载类的每个字节,并且他们可以用它们做任何他们想做的事:)。
Yes, it is possible to do dynamic implementations of an interface at runtime, and to manipulate the compiled bytecode also.
Java provides a built-in mechanism to implement interfaces at run-time, called dynamic proxy classes.
There are also good libraries like cglib or javassist, that allow you not only to implement interfaces, but also to extend classes and to manipulate bytecode at run-time (to change the behavior of a method, for example). Frameworks like Spring and Hibernate use libraries like these to make their magic, so your framework may be using some of these also.
NOTE: If you are curious, these libraries can "tweak" the bytecode because instead of using the default ClassLoader of the JVM, they load your classes using their own ClassLoader, so they have total control of every single byte of the loaded class, and they can do whatever they want with them :).