12

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.

2 Answers 2

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();
Sign up to request clarification or add additional context in comments.

4 Comments

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);
Sounds like the compiler variable is null. Make sure you have a correct Java installation. Check this out for help java.net/node/688208
Does it have to be a .java file? If I have code in a .txt file, will it still work?
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?
6

The JavaCompiler will be null if the code is running from a JRE. It needs a JDK, which includes the tools.jar.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.