I have found many references explaining how to programmatically compile a Java class using the JavaCompiler class:
JavaCompiler
JavaCompiler compiler = ToolP
JavaDocs are your friend:
http://download.oracle.com/javase/6/docs/api/javax/tools/JavaCompiler.html
Look at the last section that refers to the SimpleJavaFileObject; it shows you how to use it in conjunction with code that is stored in a String
SimpleJavaFileObject
String