Top Description Inners Methods
javax.tools

public Interface JavaCompiler

extends Tool, OptionChecker
Imports
java.io.Writer, java.net.URI, java.nio.charset.Charset, java.util.Locale, java.util.concurrent.Callable, javax.annotation.processing.Processor

Interface to invoke Java programming language compilers from programs.

The compiler might generate diagnostics during compilation (for example, error messages). If a diagnostic listener is provided, the diagnostics will be supplied to the listener. If no listener is provided, the diagnostics will be formatted in an unspecified format and written to the default output, which is System.err unless otherwise specified. Even if a diagnostic listener is supplied, some diagnostics might not fit in a Diagnostic and will be written to the default output.

A compiler tool has an associated standard file manager, which is the file manager that is native to the tool (or built-in). The standard file manager can be obtained by calling getStandardFileManager.

A compiler tool must function with any file manager as long as any additional requirements as detailed in the methods below are met. If no file manager is provided, the compiler tool will use a standard file manager such as the one returned by getStandardFileManager.

An instance implementing this interface must conform to The Java Language Specification and generate class files conforming to The Java Virtual Machine Specification. The versions of these specifications are defined in the Tool interface. Additionally, an instance of this interface supporting SourceVersion.RELEASE_6 or higher must also support annotation processing.

The compiler relies on two services: diagnostic listener and file manager. Although most classes and interfaces in this package defines an API for compilers (and tools in general) the interfaces DiagnosticListener, JavaFileManager, FileObject, and JavaFileObject are not intended to be used in applications. Instead these interfaces are intended to be implemented and used to provide customized services for a compiler and thus defines an SPI for compilers.

There are a number of classes and interfaces in this package which are designed to ease the implementation of the SPI to customize the behavior of a compiler:

StandardJavaFileManager
Every compiler which implements this interface provides a standard file manager for operating on regular files. The StandardJavaFileManager interface defines additional methods for creating file objects from regular files.

The standard file manager serves two purposes:

  • basic building block for customizing how a compiler reads and writes files
  • sharing between multiple compilation tasks

Reusing a file manager can potentially reduce overhead of scanning the file system and reading jar files. Although there might be no reduction in overhead, a standard file manager must work with multiple sequential compilations making the following example a recommended coding pattern:

File[] files1 = null ; // input for first compilation task File[] files2 = null ; // input for second compilation task JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(files1)); compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call(); Iterable<? extends JavaFileObject> compilationUnits2 = fileManager.getJavaFileObjects(files2); // use alternative method // reuse the same file manager to allow caching of jar files compiler.getTask(null, fileManager, null, null, null, compilationUnits2).call(); fileManager.close();
File[] files1 = ... ; // input for first compilation task
File[] files2 = ... ; // input for second compilation task

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

Iterable<? extends JavaFileObject> compilationUnits1 =
    fileManager.getJavaFileObjectsFromFiles(Arrays.asList(files1));
compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call();

Iterable<? extends JavaFileObject> compilationUnits2 =
    fileManager.getJavaFileObjects(files2); // use alternative method
// reuse the same file manager to allow caching of jar files
compiler.getTask(null, fileManager, null, null, null, compilationUnits2).call();

fileManager.close();
DiagnosticCollector
Used to collect diagnostics in a list, for example:
Iterable<? extends JavaFileObject> compilationUnits = null; JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null); compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits).call(); for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) { System.out.format("Error on line %d in %s%n", diagnostic.getLineNumber(), diagnostic.getSource().toUri()); } fileManager.close();
Iterable<? extends JavaFileObject> compilationUnits = ...;
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits).call();

for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
    System.out.format("Error on line %d in %s%n",
                      diagnostic.getLineNumber(),
                      diagnostic.getSource().toUri());
}

fileManager.close();
ForwardingJavaFileManager, ForwardingFileObject, and ForwardingJavaFileObject
Subclassing is not available for overriding the behavior of a standard file manager as it is created by calling a method on a compiler, not by invoking a constructor. Instead forwarding (or delegation) should be used. These classes makes it easy to forward most calls to a given file manager or file object while allowing customizing behavior. For example, consider how to log all calls to JavaFileManager#flush:
final Logger logger = null; Iterable<? extends JavaFileObject> compilationUnits = null; JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager stdFileManager = compiler.getStandardFileManager(null, null, null); JavaFileManager fileManager = new ForwardingJavaFileManager(stdFileManager) { @Override public void flush() throws IOException { logger.entering(StandardJavaFileManager.class.getName(), "flush"); super.flush(); logger.exiting(StandardJavaFileManager.class.getName(), "flush"); } }; compiler.getTask(null, fileManager, null, null, null, compilationUnits).call();
final  Logger logger = ...;
Iterable<? extends JavaFileObject> compilationUnits = ...;
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager stdFileManager = compiler.getStandardFileManager(null, null, null);
JavaFileManager fileManager = new ForwardingJavaFileManager(stdFileManager) {
    @Override
    public void flush() throws IOException {
        logger.entering(StandardJavaFileManager.class.getName(), "flush");
        super.flush();
        logger.exiting(StandardJavaFileManager.class.getName(), "flush");
    }
};
compiler.getTask(null, fileManager, null, null, null, compilationUnits).call();
SimpleJavaFileObject
This class provides a basic file object implementation which can be used as building block for creating file objects. For example, here is how to define a file object which represent source code stored in a string:
/* * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import javax.tools.SimpleJavaFileObject; import java.net.URI; /** * A file object used to represent source coming from a string. */ public class JavaSourceFromString extends SimpleJavaFileObject { /** * The source code of this "file". */ final String code; /** * Constructs a new JavaSourceFromString. * @param name the name of the compilation unit represented by this file object * @param code the source code for the compilation unit represented by this file object */ JavaSourceFromString(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; } }
/**
 * A file object used to represent source coming from a string.
 */
public class JavaSourceFromString extends SimpleJavaFileObject {
    /**
     * The source code of this "file".
     */
    final String code;

    /**
     * Constructs a new JavaSourceFromString.
     * @param name the name of the compilation unit represented by this file object
     * @param code the source code for the compilation unit represented by this file object
     */
    JavaSourceFromString(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;
    }
}
Since
1.6
See Also
DiagnosticListener, Diagnostic, JavaFileManager

Nested and Inner Type Summary

Modifier and TypeClass and Description
public static interface
JavaCompiler.CompilationTask

Interface representing a future for a compilation task.

Method Summary

Modifier and TypeMethod and Description
public StandardJavaFileManager

Returns:

the standard file manager
getStandardFileManager
(DiagnosticListener<? super JavaFileObject>
a diagnostic listener for non-fatal diagnostics; if null use the compiler's default method for reporting diagnostics
diagnosticListener
,
Locale
the locale to apply when formatting diagnostics; null means the default locale.
locale
,
Charset
the character set used for decoding bytes; if null use the platform default
charset
)

Returns a new instance of the standard file manager implementation for this tool.

public JavaCompiler.CompilationTask

Returns:

an object representing the compilation
getTask
(Writer
a Writer for additional output from the compiler; use System.err if null
out
,
JavaFileManager
a file manager; if null use the compiler's standard file manager
fileManager
,
DiagnosticListener<? super JavaFileObject>
a diagnostic listener; if null use the compiler's default method for reporting diagnostics
diagnosticListener
,
Iterable<String>
compiler options, null means no options
options
,
Iterable<String>
names of classes to be processed by annotation processing, null means no class names
classes
,
Iterable<? extends JavaFileObject>
the compilation units to compile, null means no compilation units
compilationUnits
)

Creates a future for a compilation task with the given components and arguments.

Inherited from javax.tools.OptionChecker:
isSupportedOption
Inherited from javax.tools.Tool:
getSourceVersionsnamerun

Method Detail

getStandardFileManagerback to summary
public StandardJavaFileManager getStandardFileManager(DiagnosticListener<? super JavaFileObject> diagnosticListener, Locale locale, Charset charset)

Returns a new instance of the standard file manager implementation for this tool. The file manager will use the given diagnostic listener for producing any non-fatal diagnostics. Fatal errors will be signaled with the appropriate exceptions.

The standard file manager will be automatically reopened if it is accessed after calls to flush or close. The standard file manager must be usable with other tools.

Parameters
diagnosticListener:DiagnosticListener<? super JavaFileObject>

a diagnostic listener for non-fatal diagnostics; if null use the compiler's default method for reporting diagnostics

locale:Locale

the locale to apply when formatting diagnostics; null means the default locale.

charset:Charset

the character set used for decoding bytes; if null use the platform default

Returns:StandardJavaFileManager

the standard file manager

getTaskback to summary
public JavaCompiler.CompilationTask getTask(Writer out, JavaFileManager fileManager, DiagnosticListener<? super JavaFileObject> diagnosticListener, Iterable<String> options, Iterable<String> classes, Iterable<? extends JavaFileObject> compilationUnits)

Creates a future for a compilation task with the given components and arguments. The compilation might not have completed as described in the CompilationTask interface.

If a file manager is provided, it must be able to handle all locations defined in StandardLocation.

Note that annotation processing can process both the compilation units of source code to be compiled, passed with the compilationUnits parameter, as well as class files, whose names are passed with the classes parameter.

Parameters
out:Writer

a Writer for additional output from the compiler; use System.err if null

fileManager:JavaFileManager

a file manager; if null use the compiler's standard file manager

diagnosticListener:DiagnosticListener<? super JavaFileObject>

a diagnostic listener; if null use the compiler's default method for reporting diagnostics

options:Iterable<String>

compiler options, null means no options

classes:Iterable<String>

names of classes to be processed by annotation processing, null means no class names

compilationUnits:Iterable<? extends JavaFileObject>

the compilation units to compile, null means no compilation units

Returns:JavaCompiler.CompilationTask

an object representing the compilation

Exceptions
RuntimeException:
if an unrecoverable error occurred in a user supplied component. The cause will be the error in user code.
IllegalArgumentException:
if any of the options are invalid, or if any of the given compilation units are of other kind than source
javax.tools back to summary

public Interface JavaCompiler.CompilationTask

extends Callable<Boolean>

Interface representing a future for a compilation task. The compilation task has not yet started. To start the task, call the call method.

Before calling the call method, additional aspects of the task can be configured, for example, by calling the setProcessors method.

Method Summary

Modifier and TypeMethod and Description
public void
addModules(Iterable<String>
the names of the root modules
moduleNames
)

Adds root modules to be taken into account during module resolution.

public Boolean

Returns:

true if and only all the files compiled without errors; false otherwise
call
()

Redeclares java.util.concurrent.Callable.call.

Performs this compilation task.

public void
setLocale(Locale
the locale to apply; null means apply no locale
locale
)

Sets the locale to be applied when formatting diagnostics and other localized data.

public void
setProcessors(Iterable<? extends Processor>
processors (for annotation processing)
processors
)

Sets processors (for annotation processing).

Method Detail

addModulesback to summary
public void addModules(Iterable<String> moduleNames)

Adds root modules to be taken into account during module resolution. Invalid module names may cause either IllegalArgumentException to be thrown, or diagnostics to be reported when the task is started.

Parameters
moduleNames:Iterable<String>

the names of the root modules

Exceptions
IllegalArgumentException:
may be thrown for some invalid module names
IllegalStateException:
if the task has started
Since
9
callback to summary
public Boolean call()

Redeclares java.util.concurrent.Callable.call.

Performs this compilation task. The compilation may only be performed once. Subsequent calls to this method throw IllegalStateException.

Returns:Boolean

true if and only all the files compiled without errors; false otherwise

Annotations
@Override
Exceptions
RuntimeException:
if an unrecoverable error occurred in a user-supplied component. The cause will be the error in user code.
IllegalStateException:
if called more than once
setLocaleback to summary
public void setLocale(Locale locale)

Sets the locale to be applied when formatting diagnostics and other localized data.

Parameters
locale:Locale

the locale to apply; null means apply no locale

Exceptions
IllegalStateException:
if the task has started
setProcessorsback to summary
public void setProcessors(Iterable<? extends Processor> processors)

Sets processors (for annotation processing). This will bypass the normal discovery mechanism.

Parameters
processors:Iterable<? extends Processor>

processors (for annotation processing)

Exceptions
IllegalStateException:
if the task has started