## Compiling Java code

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 .

### Compiling code

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);

### Using the batch compiler

#### Finding the batch compiler

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.

#### Running the batch compiler

- Using the main method.
The Main class has a main method. This is the classical way to invoke the batch compiler on a command-line.

- For example on a command-line:

  `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`

- For example in a java source:

  `org.eclipse.jdt.internal.compiler.batch.Main.main(new String[] {"-classpath", "rt.jar", "A.java"});`

- Using the static compile(String) method.

  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");`

#### Which options are available?

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.1 (major version: 45 minor: 3) 1.2 (major version: 46 minor: 0) 1.3 (major version: 47 minor: 0) 1.4 (major version: 48 minor: 0) 1.5, 5 or 5.0 (major version: 49 minor: 0) 1.6, 6 or 6.0 (major version: 50 minor: 0) Defaults are: 1.1 in -1.3 mode 1.2 in -1.4 mode 1.5 in -1.5 mode 1.6 in -1.6 mode
-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: 1.3 1.4 1.5, 5 or 5.0 1.6, 6 or 6.0 Defaults are: 1.3 in -1.3 mode 1.3 in -1.4 mode 1.5 in -1.5 mode 1.6 in -1.6 mode In 1.4, assert is treated as a keyword. In 1.5 and 1.6, enum and assert are treated as a keywords.
Warning options
-warn: allDeprecation allJavadoc assertIdentifier boxing charConcat conditionAssign constructorName dep-ann deprecation discouraged emptyBlock enumSwitch fallthrough fieldHiding finalBound finally forbidden hiding incomplete-switch indirectStatic intfAnnotation intfNonInherited javadoc localHiding maskedCatchBlocks nls noEffectAssign null over-ann paramAssign pkgDefaultMethod raw semicolon serial specialParamHiding static-access staticReceiver suppress synthetic-access syntheticAccess tasks(<task1>|...|<taskN>) typeHiding unchecked unnecessaryElse unqualified-field-access unqualifiedField unused unusedArgument unusedImport unusedLabel unusedLocal unusedPrivate unusedThrown uselessTypeCheck varargsCast warningToken | 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
allDeprecation | deprecation even inside deprecated code
allJavadoc | invalid or missing javadoc
assertIdentifier | occurrence of assert used as identifier
boxing | autoboxing conversion
charConcat | when a char array is used in a string concatenation without being converted explicitly to a string
conditionAssign | possible accidental boolean assignment
constructorName | method with constructor name
dep-ann | missing @Deprecated annotation
deprecation | usage of deprecated type or member outside deprecated code
discouraged | use of types matching a discouraged access rule
emptyBlock | undocumented empty block
enumSwitch, incomplete-switch | incomplete enum switch
fallthrough | possible fall-through case
fieldHiding | field hiding another variable
finalBound | type parameter with final bound
finally | finally block not completing normally
forbidden | use of types matching a forbidden access rule
hiding | macro for fieldHiding, localHiding, typeHiding and maskedCatchBlock
indirectStatic | indirect reference to static member
intfAnnotation | annotation type used as super interface
intfNonInherited | interface non-inherited method compatibility
javadoc | invalid javadoc
localHiding | local variable hiding another variable
maskedCatchBlocks | hidden catch block
nls | non-nls string literals (lacking of tags //$NON-NLS-<n>)
noEffectAssign | assignment with no effect
null | missing or redundant null check
over-ann | missing @Override annotation
paramAssign | assignment to a parameter
pkgDefaultMethod | attempt to override package-default method
raw | usage a of raw type (instead of a parametrized type)
semicolon | unnecessary semicolon or empty statement
serial | missing serialVersionUID
specialParamHiding | constructor or setter parameter hiding another field
static-access | macro for indirectStatic and staticReceiver
staticReceiver | if a non static receiver is used to get a static field or call a static method
suppress | enable @SuppressWarnings
syntheticAccess, synthetic-access | when performing synthetic access for innerclass
tasks | enable support for tasks tags in source code
typeHiding | type parameter hiding another type
unchecked | unchecked type operation
unnecessaryElse | unnecessary else clause
unqualified-field-access, unqualifiedField | unqualified reference to field
unused | macro for unusedArgument, unusedImport, unusedLabel, unusedLocal, unusedPrivate and unusedThrown
unusedArgument | unused method argument
unusedImport | unused import reference
unusedLabel | unused label
unusedLocal | unused local variable
unusedPrivate | unused private member declaration
unusedThrown | unused declared thrown exception
uselessTypeCheck | unnecessary cast/instanceof operation
varargsCast | varargs argument need explicit cast
warningToken | unhandled warning token in @SuppressWarnings
-nowarn | No warning (equivalent to -warn:none)
-deprecation | Equivalent to -warn:deprecation.
Debug options
-g[:none|:lines,vars,source] | Set the debug attributes level
-g | All debug info (equivalent to -g:lines,vars,source)
-g:none | No debug info
-g:[lines,vars,source] | Selective debug info
-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 (at line 8)...` 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.

#### Examples

`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.

### Using the ant javac adapter

The Eclipse compiler can be used inside an Ant script using the javac adapter. In order to use the Eclipse compiler, you simply need to define the build.compiler property in your script. Here is a small example.

    <?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.

### Problem determination

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.

### Excluding warnings using `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:

- all to suppress all warnings
- boxing to suppress warnings relative to boxing/unboxing operations
- cast to suppress warnings relative to cast operations
- dep-ann to suppress warnings relative to deprecated annotation
- deprecation to suppress warnings relative to deprecation
- fallthrough to suppress warnings relative to missing breaks in switch statements
- finally to suppress warnings relative to finally block that don't return
- hiding to suppress warnings relative to locals that hide variable
- incomplete-switch to suppress warnings relative to missing entries in a switch statement (enum case)
- nls to suppress warnings relative to non-nls string literals
- null to suppress warnings relative to null analysis
- restriction to suppress warnings relative to usage of discouraged or forbidden references
- serial to suppress warnings relative to missing serialVersionUID field for a serializable class
- static-access to suppress warnings relative to incorrect static access
- synthetic-access to suppress warnings relative to unoptimized access from inner classes
- unchecked to suppress warnings relative to unchecked operations
- unqualified-field-access to suppress warnings relative to field access unqualified
- unused to suppress warnings relative to unused code