Essentially, you want to somehow modify an arbitrary piece of code.
To do this in general, you pretty much have to be able to parse the text so that you can place structures in appropriate structured places. A commonly used pattern is text; There is no structure to hang a hat.
The most reliable way to do this is to use a source-to-source conversion system. Such a tool allows you to explicitly indicate: "If you see this, replace it with this." To achieve your goal, you would say something like: "If you see a set of class declarations in class X, add this class", usually indicated as
a rewritesto b if condition c
DMS Software Reengineering Toolkit - a program conversion tool that will read the source code, build compiler data structures (AST, symbol tables, flow graphs), allow you to apply source rewrites to the source of the code presented in the form of these structures, using the source templates for matching / replacement , and then regenerate a reliable source from the result.
DMS has a / prettyprinters parser for many languages, including Java (1.4 / 1.5 / 1.6), C, C ++, C #, COBOL, PHP, JavaScript, ...
For your task with adding a parameter using DMS, you should write the following conversion rule:
add_string_parameter(r:result_type,m:IDENTIFIER,p:parameter_list): method_signature->method_signature = " \r \m ( \p ) " -> " \r \m ( \p , String PARAMETER ) " if m="getTemplateText";
( β corresponds to "rewritesto"). This only recognizes method signatures (by searching for AST, not source code). Quotation markers are meta-quotes containing fragments of your target language, and you must distinguish between the text of the target language and the text in the language of the rules. r, m, p - meta-variables that must correspond to specific structures, as indicated by the signature of the rule; \ r \ m \ p are meta-expressions in the target text, which states that this structure must be present. The left side of "\ r \ m (\ p)" corresponds to the signatures and connects r, m, p with the AST structures supporting it; the right side indicates the substitution, in which the associated values ββof r, m, p are substituted to obtain a replacement. The conditional "if" should insist that only the modified desired method be changed; you may need a more complicated condition if you have a large pile of code and want to use only a specific method.