The JDT plug-ins include an incremental and batch Java compiler for building Java .class files from source code. There is no direct API provided by the compiler. It is installed as a builder on Java projects. Compilation is triggered using standard platform build mechanisms.
The platform build mechanism is described in detail in Incremental project builders .
You can programmatically compile the Java source files in a project using the build API.
IProject myProject; IProgressMonitor myProgressMonitor; myProject.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, myProgressMonitor);
For a Java project, this invokes the Java incremental project builder (along with any other incremental project builders that have been added to the project's build spec). The generated .class files are written to the designated output folder. Additional resource files are also copied to the output folder.
In the case of a full batch build, all the .class files in the output folder may be 'scrubbed' to ensure that no stale files are found. This is controlled using a JDT Core Builder Option (CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER). The default for this option is to clean output folders. Unless this option is reset, you must ensure that you place all .class files for which you do not have corresponding source files in a separate class file folder on the classpath instead of the output folder.
The
incremental and batch builders can be configured with other options that
control which resources are copied to the output folder. The following sample shows how to set up a resource filter so that files ending with '.ignore' and folders named 'META-INF',
are not copied to the output folder:
Hashtable options = JavaCore.getOptions();
options.put(JavaCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER, "*.ignore,META-INF/");
JavaCore.setOptions(options);
Filenames are filtered out if they match one of the supplied patterns. Entire folders are filtered out if their name matches one of the supplied folder names which end in a path separator.
The incremental and batch builders can also be configured to only generate a single error when the .classpath file has errors. This option is set by default and eliminates numerous errors. See JDT Core Builder Options for a complete list of builder-related options and their defaults.
The compiler can also be configured using JavaCore options. For example, you can define the severity that should be used for different kinds of problems that are found during compilation. See JDT Core Compiler Options for a complete list of compiler-related options and their defaults.
When programmatically configuring options for the builder or compiler, you should specify the scope of the option. For example, setting up a resource filter may apply to a particular project only:
Hashtable options = myProject.getOptions(false); // get only the options set up in this project options.put(JavaCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER, "*.ignore,META-INF/"); myProject.setOptions(options);
The batch compiler class is located in the internal classes of the
JDT Core plug-in.
The name of the class is org.eclipse.jdt.internal.compiler.batch.Main. It
is packaged into plugins/org.eclipse.jdt.core_3.2.0.jar
. Since 3.2, it is also available as a separate download.
The name of the file is ecj.jar. Its corresponding source is also available. To get them, go to the download page and
search for the section JDT Core Batch Compiler. This jar contains the batch compiler and the javac ant adapter.
So it can be used as a standalone application and inside an Ant build outside of Eclipse.
java -classpath org.eclipse.jdt.core_3.2.0.jar org.eclipse.jdt.internal.compiler.batch.Main
-classpath rt.jar A.java
or:
java -jar org.eclipse.jdt.core_3.2.0.jar -classpath rt.jar A.java
org.eclipse.jdt.internal.compiler.batch.Main.main(new
String[] {"-classpath", "rt.jar", "A.java"});
The compile(String)
method is a convenient method to invoke
the batch compiler in a java application. Instead of
org.eclipse.jdt.internal.compiler.batch.Main.main(new
String[] {"-classpath", "rt.jar", "A.java"});
you can simply write org.eclipse.jdt.internal.compiler.batch.Main.compile("-classpath
rt.jar A.java");
With the orange background, these are suggested options.
Name | Usage | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Classpath options | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-bootclasspath <dir 1>;<dir 2>;...;<dir P> | This is a list of directories or jar files used to bootstrap the class files used by the compiler. By default the libraries of the running
VM are used. Entries are separated by the platform path separator.
Each directory or file can specify access rules for types between '[' and ']'. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-cp -classpath <dir 1>;<dir 2>;...;<dir P> |
This is a list of directories or jar files used to compile the source files. The default value is the value of the property "java.class.path".
Entries are separated by the platform path separator.
Each directory or file can specify access rules for types between '[' and ']' (e.g. [-X] to forbid access to type X, [~X] to discourage access to type X, [+p/X:-p/*] to forbid access to all types in package p but allow access to p/X). |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-extdirs <dir 1>;<dir 2>;...;<dir P> | This is a list of directories used to specify the location of extension zip/jar files. Entries are separated by the platform path separator. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-endorseddirs <dir 1>;<dir 2>;...;<dir P> | This is a list of directories used to specify the location of endorsed zip/jar files. Entries are separated by the platform path separator. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-sourcepath <dir 1>;<dir 2>;...;<dir P> | This is a list of directories used to specify the source files. Entries are separated by the platform path separator.
Each directory can specify access rules for types between '[' and ']'. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-d <dir 1>|none | This is used to specify in which directory the generated .class files should be dumped. If it is omitted, no package directory structure is created. If you want to generate no .class file at all, use -d none. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-encoding <encoding name> | Specify default source encoding format (custom encoding can also be specified on a per file basis by suffixing each input source file/folder name with [<encoding name>], for example X.java[utf8]). | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Compliance options | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-target 1.1|1.2|1.3|1.4|1.5|5|5.0|1.6|6|6.0 | This specifies the .class file target setting.
The possible value are:
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-1.3 | Set compliance level to 1.3. Implicit -source 1.3 -target 1.1. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-1.4 | Set compliance level to 1.4 (default). Implicit -source 1.3 -target 1.2. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-1.5 | Set compliance level to 1.5. Implicit -source 1.5 -target 1.5. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-1.6 | Set compliance level to 1.6. Implicit -source 1.6 -target 1.6. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-source 1.3|1.4|1.5|5|5.0|1.6|6|6.0 | This is used to specify the source level expected by the compiler. The possible value are:
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Warning options | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-warn:allDeprecation |
Set warning level. e.g. -warn:unusedLocal,deprecation In red are the default settings.
-warn:none disable all warnings -warn:<warnings separated by ,> enable exactly the listed warnings -warn:+<warnings separated by ,> enable additional warnings -warn:-<warnings separated by ,> disable specific warnings
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-nowarn | No warning (equivalent to -warn:none) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-deprecation | Equivalent to -warn:deprecation. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Debug options | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-g[:none|:lines,vars,source] | Set the debug attributes level
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-preserveAllLocals | Explicitly request the compiler to preserve all local variables (for debug purpose). If omitted, the compiler will remove unused locals. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Ignored options (for compatibility with javac options) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-J<option> | pass option to the virtual machine | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-X<option> | specify non-standard option. -Xemacs is not ignored. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-X | print non-standard options and exit | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-O | optimize for execution time | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Advanced options | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
@<file> | Read command-line arguments from file | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-maxProblems <n> | Max number of problems per compilation unit (100 by default) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-log <filename> | Specify a log file in which all output from the compiler will be dumped. This is really useful if you want to debug the batch compiler or get a file which contains all errors and warnings from a batch build. If the extension is .xml, the generated log will be an xml file. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-Xemacs | Use emacs style to present errors and warnings locations into the console
and regular text logs. XML logs are unaffected by this option. With this option
active, the message:
2. WARNING in /workspace/X.java is presented as:
/workspace/X.java:8: warning: The method... |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-proceedOnError | Keep compiling in spite of errors, dumping class files with problem methods or problem types. This is recommended only if you want to be able to run your application even if you have remaining errors. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-verbose | Print accessed/processed compilation units in the console or the log file if specified. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-referenceInfo | Compute reference info. This is useful only if connected to the builder. The reference infos are useless otherwise. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-progress | Show progress (only in -log mode). | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-time | Display speed information. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-noExit | Do not call System.exit(n) at end of compilation (n=0 if no error). | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-repeat <n> | Repeat compilation process <n> times (perf analysis). | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-inlineJSR | Inline JSR bytecode (implicit if target >= 1.5). | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-enableJavadoc | Consider references inside javadoc. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Helping options | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-? -help | Display the help message. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-v -version | Display the build number of the compiler. This is very useful to report a bug. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-showversion | Display the build number of the compiler and continue. This is very useful to report a bug. |
d:\temp -classpath rt.jar -time -g -d d:/tmp
|
It compiles all source files in d:\temp and its subfolders. The classpath is simply rt.jar. It generates all debug attributes and all generated .class files are dumped in d:\tmp. The speed of the compiler will be displayed once the batch process is completed. |
d:\temp\Test.java -classpath d:\temp;rt.jar -g:none
|
It compiles only Test.java and its dependant files if any, retrieving dependant files from d:\temp. The classpath is d:\temp followed by rt.jar, which means that all necessary classes are searched first in d:\temp and then in rt.jar. It generates no debug attributes and all generated .class files are dumped in d:\temp. |
<?xml version="1.0" encoding="UTF-8"?> <project name="compile" default="main" basedir="../."> <property name="build.compiler" value="org.eclipse.jdt.core.JDTCompilerAdapter"/> <property name="root" value="${basedir}/src"/> <property name="destdir" value="d:/temp/bin" /> <target name="main"> <javac srcdir="${root}" destdir="${destdir}" debug="on" nowarn="on" extdirs="d:/extdirs" source="1.4"> <classpath> <pathelement location="${basedir}/../org.eclipse.jdt.core/bin"/> </classpath> </javac> </target> </project>The syntax used for the javac Ant task can be found in the Ant javac task documentation. The current adapter supports the Javac Ant task 1.4.1 up to 1.6.5 versions.
If you are using a version above 1.5.0, you can use the nested compiler argument element to specify compiler specific options.
... <javac srcdir="${root}" destdir="${destdir}" debug="on" nowarn="on" extdirs="d:/extdirs" source="1.4"> <classpath> <pathelement location="${basedir}/../org.eclipse.jdt.core/bin"/> </classpath> <compilerarg compiler="org.eclipse.jdt.core.JDTCompilerAdapter" line="-1.5 -warn:+boxing"/> </javac> ...
To prevent from getting compiler dependant scripts, we advise you to use the compiler argument set to org.eclipse.jdt.core.JDTCompilerAdapter
.
If this is not set, the script can only be used with the Eclipse compiler. If set, the nested compiler argument is ignored if the name is different from the
compiler name specified by the build.compiler
property.
JDT Core defines a specialized marker (marker type "org.eclipse.jdt.core.problem ") to denote compilation problems. To programmatically discover problems detected by the compiler, the standard platform marker protocol should be used. See Resource Markers for an overview of using markers.
The following snippet finds all Java problem markers in a compilation unit.
public IMarker[] findJavaProblemMarkers(ICompilationUnit cu) throws CoreException { IResource javaSourceFile = cu.getUnderlyingResource(); IMarker[] markers = javaSourceFile.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE); }
Java problem markers are maintained by the Java project builder and are removed automatically as problems are resolved and the Java source is recompiled.
The problem id value is set to one of the constants defined in IProblem . The problem's id is reliable, but the message is localized and therefore can be changed according to the default locale. The constants defined in IProblem are self-descriptive.
An implementation of
IProblemRequestor
should be defined to collect the problems discovered during a Java operation.
Working copies can be reconciled with problem detection if a
IProblemRequestor
has been supplied for the working copy creation. To achieve this, you
can use the
reconcile method. Here is an example:
ICompilationUnit unit = ..; // get some compilation unit
// create requestor for accumulating discovered problems
IProblemRequestor problemRequestor = new IProblemRequestor() {
public void acceptProblem(IProblem problem) {
System.out.println(problem.getID() + ": " + problem.getMessage());
}
public void beginReporting() {}
public void endReporting() {}
public boolean isActive() { return true; } // will detect problems if active
};
// use working copy to hold source with error
ICompilationUnit workingCopy = unit.getWorkingCopy(new WorkingCopyOwner() {}, problemRequestor, null);
((IOpenable)workingCopy).getBuffer().setContents("public class X extends Zork {}");
// trigger reconciliation
workingCopy.reconcile(NO_AST, true, null, null);
You can add an action on the reported problems in the acceptProblem(IProblem)
method. In this example, the reported problem will be that Zork cannot
be resolved or is not a valid superclass and its id is IProblem.SuperclassNotFound.
SuppressWarnings
Java 5.0 offers the option to the user to disable compilation warnings relative to a subset of a compilation unit using
the annotation java.lang.SuppressWarning
.
@SuppressWarning("unused") public void foo() { String s; }
Without the annotation, the compiler would complain that the local variable s
is never used.
With the annotation, the compiler silently ignores this warning locally to the foo
method. This enables to
keep the warnings in other locations of the same compilation unit or the same project.
The list of tokens that can be used inside an SuppressWarning
annotation is: