
Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:
Once the early-adopter seats are all used, the price will go up and stay at $33/year.
Last updated: May 5, 2025
In Java development, compilation is the first defense against syntax errors, type mismatches, and other issues that can derail a project. While traditional workflows rely on manual compilation, modern applications demand dynamic compilation checks. For instance:
The Java Compiler API enables these scenarios by allowing code compilation programmatically within Java applications. Platforms like LeetCode or Codecademy validate user-submitted code instantly. When users click “Run,” the backend compiles the snippet using tools like the Compiler API, checks for errors, and executes it in a sandboxed environment. Programmatic compilation powers this immediate feedback loop.
In this tutorial, we’ll explore how to leverage this powerful tool.
The Java Compiler API resides within the javax.tools package and provides programmatic access to the Java compiler. This API is crucial for dynamic compilation tasks where code needs to be verified or executed at runtime.
Key components of the Compiler API include:
These components work together to enable flexible and efficient dynamic compilation within Java applications.
Let’s examine how the compilation process works.
The Compiler API is available by default in JDK environments without needing any external dependencies. Now, let’s see how to compile in-memory Java code from .java files.
To compile code stored as a string, we first need to create an in-memory representation of the source file. We do this by extending the SimpleJavaFileObject class:
public class InMemoryJavaFile extends SimpleJavaFileObject {
private final String code;
protected InMemoryJavaFile(String name, String code) {
super(URI.create("string:///" + name.replace('.', '/') + Kind.SOURCE.extension),
Kind.SOURCE);
this.code = code;
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return code;
}
}
This class represents the Java code as an in-memory JavaFileObject, enabling us to pass source code directly to the compiler without needing a physical file.
Next, let’s create a utility method to compile Java code and capture diagnostics:
private boolean compile(Iterable<? extends JavaFileObject> compilationUnits) {
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
JavaCompiler.CompilationTask task = compiler.getTask(
null,
standardFileManager,
diagnostics,
null,
null,
compilationUnits
);
boolean success = task.call();
for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
System.out.println(diagnostic.getMessage(null));
}
return success;
}
The compile() method handles Java source compilation through the Compiler API, starting with a DiagnosticCollector to capture compilation messages.
The central compiler.getTask() call accepts six parameters: null for the writer (defaulting to System.err), a standard file manager for handling source files, the diagnostic collector for compilation messages, null for compiler options (using defaults instead of custom flags), null for annotation processing classes (as no specific types need processing), and the provided compilation units containing source files to compile. After executing task.call() , the method logs all diagnostic messages and returns a boolean indicating compilation success.
To make compilation easier to use in client code or test cases, let’s introduce a wrapper method that compiles Java code directly from a String:
public boolean compileFromString(String className, String sourceCode) {
JavaFileObject sourceObject = new InMemoryJavaFile(className, sourceCode);
return compile(Collections.singletonList(sourceObject));
}
Here, we create an instance of the InMemoryJavaFile class from earlier and wrap it in a singleton list to pass to the actual compile() method.
Now that we’ve implemented a method to compile Java code dynamically, let’s test it using both valid and invalid code snippets. This confirms that the API correctly identifies syntax errors and returns appropriate diagnostics:
@Test
void givenSimpleHelloWorldClass_whenCompiledFromString_thenCompilationSucceeds() {
String className = "HelloWorld";
String sourceCode = "public class HelloWorld {\n" +
" public static void main(String[] args) {\n" +
" System.out.println(\"Hello, World!\");\n" +
" }\n" +
"}";
boolean result = compilerUtil.compileFromString(className, sourceCode);
assertTrue(result, "Compilation should succeed");
// Check if the class file was created
Path classFile = compilerUtil.getOutputDirectory().resolve(className + ".class");
assertTrue(Files.exists(classFile), "Class file should be created");
}
This test confirms that the compiler processes and compiles valid Java source code into an executable class file generated in the expected output directory.
Next, we verify error capturing by testing code with a syntax error:
@Test
void givenClassWithSyntaxError_whenCompiledFromString_thenCompilationFails() {
String className = "ErrorClass";
String sourceCode = "public class ErrorClass {\n" +
" public static void main(String[] args) {\n" +
" System.out.println(\"This has an error\")\n" +
" }\n" +
"}";
boolean result = compilerUtil.compileFromString(className, sourceCode);
assertFalse(result, "Compilation should fail due to syntax error");
Path classFile = compilerUtil.getOutputDirectory().resolve(className + ".class");
assertFalse(Files.exists(classFile), "No class file should be created for failed compilation");
}
Since the compilation fails, no .class file is created, confirming that errors are properly captured.
In this article, we explored the Java Compiler API and its role in programmatic code compilation. We learned how to compile in-memory source code, capture diagnostics, and execute compilation dynamically.
By leveraging the Compiler API, we can:
Whether we’re building an automated grading system, a plugin system, or a tool for dynamic Java execution, the Java Compiler API provides a powerful and flexible solution.
As always, the full source code for this article is over on GitHub.