See http://java.sun.com/j2se/1.5.0/docs/tooldocs/solaris/javac.html#proginterface
Assuming that the user input consists of only simple statements (without method and/or class declarations and such), the following method generated a corresponding source file, compiles and executes it. Currently, the output is not collected, but I'm pretty sure you'll be able to adopt the code to your individual needs.
public void generateAndExecute(String in) throws Exception {
// create the source file
File f = new File(new File(System.getProperty("user.dir")), "Base.java");
f.deleteOnExit();
BufferedWriter w = new BufferedWriter(new FileWriter(f));
w.write("public class Base {");
w.newLine();
w.write("public static void main(String[] args) {");
w.newLine();
w.write(in);
w.newLine();
w.write("}}");
w.newLine();
w.close();
// search for directory in class path
String cp = System.getProperty("java.class.path");
StringTokenizer st = new StringTokenizer(cp, System.getProperty("path.separator"));
String targetDir = null;
while (st.hasMoreTokens() && targetDir == null) {
File tmp = new File(st.nextToken());
if (tmp.isDirectory())
targetDir = tmp.getAbsolutePath();
}
if (targetDir == null)
throw new FileNotFoundException("No directory entries in class path!");
// compile the source file
int compileResult = Main.compile(new String[] {
"-sourcepath", f.getParentFile().getAbsolutePath(),
"-d", targetDir,
f.getName()
});
// execute the source file
switch (compileResult) {
case 0:
Class<?> clazz = Class.forName("Base");
Class<? extends Object> stringArrayClass = Array.newInstance(String.class, 0).getClass();
Method mainMethod = clazz.getMethod("main", stringArrayClass);
mainMethod.invoke((Object) null, (Object) null);
default:
throw new Exception("Compiler exited with return value other than 0!");
}
}