在编译的Java类中重写方法调用 [英] Rewriting method calls within compiled Java classes

查看:149
本文介绍了在编译的Java类中重写方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在解析编译的类文件的同时用方法体内的anther类调用替换对给定类的调用...

或换句话说,是否有一种方法可以检测到在方法中给定类并使用等替换该方法的那一部分javaassist

I want to replace calls to a given class with calls to anther class within a method body whilst parsing compiled class files...
or put another way, is there a method of detecting usages of a given class in a method and replacing just that part of the method using something like javaassist.

例如..如果我的编译版本为

for example.. if I had the compiled version of

class A { public int m() { int i = 2; B.multiply(i,i); return i; } }

是否有一种检测B的使用然后改变代码执行的方法

is there a method of detecting the use of B and then altering the code to perform

class A { public int m() { int i = 2; C.divide(i,i); return i; } }

我知道另一种方法是编写一个解析器来grep源文件以供使用但是我更喜欢更优雅的解决方案,例如使用反射来生成新的编译类文件。

I know the alternative would be to write a parser to grep the source files for usages but I would prefer a more elegant solution such as using reflection to generate new compiled class files.

有什么想法吗?

推荐答案

正如@djna所说,它是可以在加载之前修改字节码文件,但是你可能不想这样做:

As @djna says, it is possible to modify bytecode files before you load them, but you probably do not want to do this:


  • 执行代码修改的代码是可能很复杂且难以维护。

  • 修改后的代码可能很难调试。首先,源级调试器将显示不再与您实际编辑的代码对应的源代码。

字节码在某些情况下,重写很有用。例如,JDO实现使用字节码重写来将对象成员提取替换为对持久性库的调用。但是,如果您可以访问这些文件的源代码,则可以通过预处理(或生成)源代码获得更好(即更易维护)的解决方案。

Bytecode rewriting is useful in certain cases. For example, JDO implementations use bytecode rewriting to replace object member fetches with calls into the persistence libraries. However, if you have access to the source code for these files, you'll get a better (i.e. more maintainable) solution by preprocessing (or generating) the source code.

编辑:AOP或Groovy听起来也是可行的选择,具体取决于您预期的重写程度。

and AOP or Groovy sound like viable alternatives too, depending on the extent of rewriting that you anticipate doing.

这篇关于在编译的Java类中重写方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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