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/Ec开发者_如何学Golipse 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
You can achieve code generation using JET templates or write custom annotation processors. Note: on a different note, Aspect oriented frameworks realise this using a concept called as code weaving , when the point-cuts are defined.
If you want to modify a source code file, you need a program transformation system. The DMS Software Reengineering Toolkit is a program transformation tool that will read source code, build compiler data structures (ASTs, symbol tables, flow graphs), allow you to apply source-to-source rewrites to the code represented as those structures, using source patterns to match/replace, and then regenerate valid source from the result.
DMS has parser/prettyprinters for many languages, including Java, C, C++, C#, COBOL, PHP, JavaScript, ...
If you are trying to edit the source code and not byte code, You can use the ASTRewrite class of Eclipse JDT's AST library to modify an existing java source code file. You can fine the documentation here.. ASTRewrite
You can find some samples here.. Using ASTRewrite
If you insist on working this out with code generation, what you could do is generate a Stub class for Test class, then has Test class extends the Stub class. Like this
class Test extends TestStub {
@Override
public void foo() {
super.foo();
}
}
// Generated stub class
class TestStub {
public void foo() {
System.out.println("hello world");
}
}
精彩评论