I wanted to take this further and generate a larger Apex class via automation. Doing so I found some special considerations due to use of JSON to pass the code that I wanted to note to help others potentially if they want to do same.
First of all I had to escape use of backslashes (replace occurrences of \
with \\
). In fact, because I was coding in Apex (creating a Salesforce class from within Salesforce), I had to even escape them in my source code that was massaging the class code so my apex statement became...
string bodystring = batchCode.replace('\\','\\\\');
And then I also needed to escape the newline characters in the code (replace occurrences of \n
with \\n
).
Other source code I was working with had tab characters in it and those caused issues with JSON deserialization. So added mycode.replace('\t',' ')
to clean them out of the code.
With those adjustments to my code I was able to create Apex classes via automation.