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