1. Introduction
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:
- An educational platform that validates student code submissions in real time
- A CI/CD pipeline that compiles generated code snippets before deployment
- A low-code tool that dynamically compiles user-defined logic
- A Hot Code Reload system that instantly reloads developer changes
- Creating Java plugins
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.
2. Java Compiler API Overview
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:
- JavaCompiler: The main compiler instance that initiates compilation tasks
- JavaFileObject: Represents Java source or class files, either in-memory or file-based
- StandardJavaFileManager: Manages input and output files during the compilation process
- DiagnosticCollector: Captures compilation diagnostics such as errors and warnings
These components work together to enable flexible and efficient dynamic compilation within Java applications.
Let’s examine how the compilation process works.
3. Step-by-Step: Implementing a Compilation Check
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.
3.1. Create an In-Memory Java Source
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.
3.2. How the Compile API Works
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.
3.3. Compile From In-Memory String
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.
3.4. Testing the Compiler
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.
4. Conclusion
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:
- Automate compilation workflows in CI/CD pipelines, educational platforms, and low-code environments
- Validate and execute user-defined code dynamically within applications
- Improve debugging and error handling by capturing detailed diagnostics
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.
The code backing this article is available on GitHub. Once you're
logged in as a Baeldung Pro Member, start learning and coding on the project.