I'm currently creating a personal (maybe public) java terminal. I want to create a command that will create + compile a Java file on execution, except I'm not too sure on how to actually do this. Is it possible? Or am I just dreaming?
-
Check Java scripting **javax.script** technology; for example: http://java.sun.com/developer/technicalArticles/J2SE/Desktop/scripting/ – ecle Feb 26 '12 at 10:20
3 Answers
You could also use Groovy - it's quite handy if you just want to compile and run a line or two of Java code from within your application. The application may be in regular Java, with Groovy used only for compilation of the dynamically generated code. Whichever solution you choose, be careful, as executing user input as code can lead to security issues (vulnerability to injection attacks).

- 9,855
- 1
- 32
- 51
-
This is a problem, because I want a piece of code to compile a complete Java file. – Nathan Kreider Feb 26 '12 at 11:16
-
In this case, check out Andrew Thompson's answer. You could also try to use [JavaCompiler class](http://docs.oracle.com/javase/6/docs/api/javax/tools/JavaCompiler.html) directly. Even calling the javac executable on some temporary file where you would put the sources, would work, but it's not as elegant or portable as the other solutions people have suggested. – Michał Kosmulski Feb 26 '12 at 13:10
compile a Java file
See the STBC. It uses the JavaCompiler
to compile the code in the text area.

- 168,117
- 40
- 217
- 433
I agree with @eee's comment that javax.script
is probably a very nice fit for your project, script code is easier to deal with than Java code. I've successfully used it in the past for a plugin API, I don't remember having had any problems to get it up and running.
Most projects that I know of that compile real Java at runtime use the Eclipse compiler to do so. The Java 6 javac
can be accessed completely programmatically as well. I've never used either of these myself. These two and some other compilers can be accessed via Commons-JCI if desired.

- 17,296
- 2
- 61
- 80
-
Is it really necessary to learn all this? I'm not looking for anything advanced right now, as I am just learning the basics of it. Once I have everything down pat, I will upgrade all of my code, making it all secure. – Nathan Kreider Feb 26 '12 at 11:14
-
It's not necessary to learn *all* of it, just pick something and go with that. If you're on Java 7, then Andrew Thompson's answer is probably the thing to use. – Barend Feb 27 '12 at 20:52