+2  A: 

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

uthark
@uthark: "source code instrumentation" != "byte code instrumentation". The original specifically talks about src code and AST so suggesting byte code instrumentation doesn't look correct.
Webinator
@uthark: oops sorry, I misread the question, he's actually after byte code instrumentation. somehow I thought he was after source code instrumentation.
Webinator
@uthark JavaAssist, doesn't work for java 1.5 :-(
Jay
A: 

You might look into asm.

fastcodejava
A: 

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.

questzen
A: 

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, ...

Ira Baxter