Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiling external .java files from within Java

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.

like image 373
Jeff Demanche Avatar asked Jun 04 '12 22:06

Jeff Demanche


1 Answers

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();
like image 101
GETah Avatar answered Sep 27 '22 20:09

GETah