I am making a tool that will write .java files, then (hopefully) compile those files to .class files. All in one process, the user selects a file directory where multiple .java files are written. Now I want the program to compile these Java files.
Asked
Active
Viewed 2,057 times
2 Answers
15
JavaCompiler
is your friend. Check the documentation here
And here an example on how you could use the compiler API
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromStrings(Arrays.asList("YouFileToCompile.java"));
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, null,
null, compilationUnits);
boolean success = task.call();
fileManager.close();

Jean-François Savard
- 20,626
- 7
- 49
- 76

GETah
- 20,922
- 7
- 61
- 103
-
I tried this, and replaced the "YouFileToCompile.java" with an absolute path (problem?) now I get a NullPointerException at: StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null); – Jeff Demanche Jun 04 '12 at 22:33
-
Sounds like the `compiler` variable is `null`. Make sure you have a correct Java installation. Check this out for help http://www.java.net/node/688208 – GETah Jun 04 '12 at 22:41
-
Does it have to be a .java file? If I have code in a .txt file, will it still work? – JD9999 Jul 05 '16 at 04:44
-
Also, if the code needs a dependency e.g. ASM, do I need to compile ASM with the app, or can I just have it in my main application? – JD9999 Jul 05 '16 at 04:50
6
The JavaCompiler
will be null
if the code is running from a JRE. It needs a JDK, which includes the tools.jar
.

Andrew Thompson
- 168,117
- 40
- 217
- 433