The Compiler API in Java

There are quite a few tools that need to compile Java code. Obviously, devel­opment environments and programs that teach Java programming are among them, as well as testing and build automation tools. Another example is the processing of JavaServer Pages—web pages with embedded Java statements.

1. Invoking the Compiler

It is very easy to invoke the compiler. Here is a sample call:

JavaCompiler compiler = TootProvider.getSystemJavaCompiter();

OutputStream outStream = . . .;

OutputStream errStream = . . .;

int result =, outStream, errStream,

“-sourcepath”, “src”, “”);

A result value of 0 indicates successful compilation.

The compiler sends its output and error messages to the provided streams. You can set these parameters to null, in which case System.out and System.err are used. The first parameter of the run method is an input stream. As the compiler takes no console input, you can always leave it as null. (The run method is inherited from a generic Tool interface, which allows for tools that read input.)

The remaining parameters of the run method are the arguments that you would pass to javac if you invoked it on the command line. These can be options or file names.

2. Launching a Compilation Task

You can have more control over the compilation process with a CompilationTask object. This can be useful if you want to supply source from string, capture class files in memory, or process the error and warning messages.

To obtain a CompilationTask, start with a compiler object as in the preceding section. Then call

JavaCompiler.CompilationTask task = compiler.getTask(

errorWriter, // Uses System.err if null

fileManager, // Uses the standard file manager if null

diagnostics, // Uses System.err if null

options, // null if no options

classes, // For annotation processing; null if none


The last three arguments are Iterable instances. For example, a sequence of options might be specified as

Iterable<String> options = List.of(“-d”, “bin”);

The sources parameter is an Iterable of JavaFileObject instances. If you want to compile disk files, get a StandardJavaFileManager and call its getJavaFileObjects method:

StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

Iterable<JavaFileObject> sources

= fileManager.getJavaFileObjectsFromStrings(List.of(“”, “”));

JavaCompiler.CompilationTask task = compiler.getTask(

null, null, null, options, null, sources);

The getTask method returns the task object but does not yet start the compilation process. The CompilationTask class extends Callable<Boolean>. You can pass it to an ExecutorService for concurrent execution, or you can just make a synchronous call:

Boolean success =;

3. Capturing Diagnostics

To listen to error messages, install a DiagnosticListener. The listener receives a Diagnostic object whenever the compiler reports a warning or error message. The DiagnosticCollector class implements this interface. It simply collects all diag­nostics so that you can iterate through them after the compilation is complete.

DiagnosticCollector<JavaFileObject> collector = new DiagnosticCollector<>();

compiler.getTask(null, fileManager, collector, null, null, sources).call();

for (Diagnostics extends JavaFileObject> d : collector.getDiagnostics())




A Diagnostic object contains information about the problem location (including file name, line number, and column number) as well as a human-readable description.

You can also install a DiagnosticListener to the standard file manager, in case you want to trap messages about missing files:

StandardJavaFileManager fileManager

= compiler.getStandardFileManager(diagnostics, null, null);

4. Reading Source Files from Memory

If you generate source code on the fly, you can have it compiled from memory, without having to save files to disk. Use this class to hold the code:

public class StringSource extends SimpleJavaFileObject


private String code;

StringSource(String name, String code)


super(URI.create(“string:///” + name.replaceC.1,1/1) + “.java”), Kind.SOURCE); this.code = code;


public CharSequence getCharContent(boolean ignoreEncodingErrors)


return code;



Then generate the code for your classes and give the compiler a list of StringSource objects:

List<StringSource> sources = List.of(

new StringSource(className1, class1CodeString), . . .);

task = compiler.getTask(null, fileManager, diagnostics, null, null, sources);

5. Writing Byte Codes to Memory

If you compile classes on the fly, there is no need to save the class files to disk. You can save them to memory and load them right away.

First, here is a class for holding the bytes:

public class ByteArrayClass extends SimpleJavaFileObject


private ByteArrayOutputStream out;

ByteArrayClass(String name)


super(URI.create(“bytes:///” + name.replaceC.1,1/1) + “.class”), Kind.CLASS);


public byte[] getCode()


return out.toByteArray();


public OutputStream openOutputStream() throws IOException


out = new ByteArrayOutputStream(); return out;



Next, you need to configure the file manager to use these classes for output:

List<ByteArrayClass> classes = new ArrayList<>();

StandardJavaFileManager stdFileManager

= compiler.getStandardFileManager(null, null, null);

JavaFileManager fileManager

= new ForwardingJavaFileManager<JavaFileManager>(stdFileManager)


public JavaFileObject getJavaFileForOutput(Location location,

String className, Kind kind, FileObject sibling) throws IOException


if (kind == Kind.CLASS)


ByteArrayClass outfile = new ByteArrayClass(className);


return outfile;



return super.getJavaFileForOutput(location, className, kind, sibling);



To load the classes, you need a class loader (see Chapter 10):

public class ByteArrayClassLoader extends ClassLoader


private Iterable<ByteArrayClass> classes;

public ByteArrayClassLoader(Iterable<ByteArrayClass> classes)


this.classes = classes;


public Class<?> findClass(String name) throws ClassNotFoundException


for (ByteArrayClass cl : classes)


if (cl.getName().equals(7″ + name.replace(‘.’,’/’) + “.class”))


byte[] bytes = cl.getCode();

return defineClass(name, bytes, 0, bytes.length);



throw new ClassNotFoundException(name);



After compilation has finished, call the Class.forName method with that class loader:

ByteArrayClassLoader loader = new ByteArrayClassLoader(classes);

Class<?> cl = Class.forName(className, true, loader);

6. An Example: Dynamic Java Code Generation

In the JSP technology for dynamic web pages, you can mix HTML with snippets of Java code, for example:

<p>The current date and time is <b><%= new java.utit.Date() %></b>.</p>

The JSP engine dynamically compiles the Java code into a servlet. In our sample application, we use a simpler example and generate dynamic Swing code instead. The idea is that you use a GUI builder to lay out the components in a frame and specify the behavior of the components in an external file. Listing 8.4 shows a very simple example of a frame class, and Listing 8.5 shows the code for the button actions. Note that the constructor of the frame class calls an abstract method addEventHandters. Our code generator will produce a subclass that implements the addEventHandters method, adding an action listener for each line in the file. (We leave it as the proverbial exercise to the reader to extend the code generation to other event types.)

We place the subclass into a package with the name x, which we hope is not used anywhere else in the program. The generated code has the form

package x;

public class Frame extends SuperclassName


protected void addEventHandters()


componentNamei .addActionListener(event ->


code for event handleri


// repeat for the other event handlers . . .



The buitdSource method in the program of Listing 8.3 builds up this code and places it into a StringSource object. That object is passed to the Java compiler.

As described in the preceding section, we use a ForwardingJavaFiteManager that constructs a ByteArrayCtass object for every compiled class. These objects capture the class files generated when the x.Frame class is compiled. The method adds each file object to a list before returning it so that we can locate the bytecodes later.

After compilation, we use the class loader from the preceding section to load the classes stored in this list. Then, we construct and display the application’s frame class.

var loader = new ByteArrayClassLoader(classFileObjects);

var frame = (JFrame) loader.loadClass(“x.Frame”).getConstructor().newInstance();


When you click the buttons, the background color changes in the usual way. To see that the actions are dynamically compiled, change one of the lines in, for example, like this:

yellowButton=panel.setBackground(java.awt.Color.YELLOW); yellowButton.setEnabled(false);

Run the program again. Now the Yellow button is disabled after you click it. Also, have a look at the code directories. You will not find any source or class files for the classes in the x package. This example demonstrates how you can use dynamic compilation with in-memory source and class files.


Source: Horstmann Cay S. (2019), Core Java. Volume II – Advanced Features, Pearson; 11th edition.

Leave a Reply

Your email address will not be published. Required fields are marked *