I have a .java src file that looks like this:
class Test {
public void foo() {
}
}
I would like to modify foo() programatically, in the sense, say add a sysout and make it look like this:
public void foo() {
System.out.println("hello world");
}
Are there any known ways to doing this by NOT directly editing the src file (RandomAccessFile)?
A few posts on StackOverflow refer to CodeModel and Eclipse JDT’s AST for code-generation purpose. I see that these will help in code-generation from scratch, and not modify existing code. Is there an API that would let you modify existing code and which has an API as simple as CodeModel/Eclipse JDT’s AST? If not, what would be the best way to doing this?
You can use some byte-code manipulation library, e.g. JavaAssist.
See section 4.2 Altering a method body in tutorial for javaassist : http://www.csg.is.titech.ac.jp/~chiba/javassist/tutorial/tutorial2.html