Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

EclipseJDT Plug-in Developer Guide
Previous Page Home Next Page

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 JDTCore 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 JDTCore 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 JDT Core plug-in. The name of the class is org.eclipse.jdt.compiler.batch.BatchCompiler. It is packaged into plugins/org.eclipse.jdt.core_3.4.0.<qualifier>.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.

Since 3.3, this jar also contains the support for jsr199 (Compiler API) and the support for jsr269 (Annotation processing). In order to use the annotations processing support, a 1.6 VM is required.

So it can be used as a standalone application and inside an Ant build outside of Eclipse.

Running the batch compiler

  • From the command line.

    java -jar org.eclipse.jdt.core_3.4.0<qualifier>.jar -classpath rt.jar A.java

    or:

    java -jar ecj.jar -classpath rt.jar A.java

  • Using the static compile(String commandLine, PrintWriter outWriter, PrintWriter errWriter, CompilationProgress progress) method of the class BatchCompiler.
    
    org.eclipse.jdt.compiler.CompilationProgress progress = null; // instantiate your subclass
    org.eclipse.jdt.internal.compiler.batch.BatchCompiler.compile(
       "-classpath rt.jar A.java",
       new PrintWriter(System.out),
       new PrintWriter(System.err),
       progress);
    
    

    You can control how progress is reported, or how the batch compiler is canceled, by subclassing the class org.eclipse.jdt.compiler.CompilationProgress.

Which options are available?

The recommended options have an orange background.

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 ']'.

If no bootclasspath is specified, the compiler will infer it using the following system properties sun.boot.class.path, vm.boot.class.path or org.apache.harmony.boot.class.path in this order respectively.

-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).
The compiler follows the Class-Path clauses of jar files' manifests recursively and appends each referenced jar file to the end of the classpath, provided it is not on the classpath yet.
-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 to 1.7 or (5, 5.0, etc) 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)
  • 1.7, 7 or 7.0 (major version: 51 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.7 in -1.7 mode

clcd1.1 can be used to generate the StackMap attribute.

-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.
-1.7 Set compliance level to 1.7. Implicit -source 1.7 -target 1.7.
-source 1.1 to 1.7 or (5, 5.0, etc) 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
  • 1.7, 7 or 7.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
  • 1.7 in -1.7 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 -help:warn Display advanced warning options
-warn:
allDeadCode
allDeprecation
allJavadoc
assertIdentifier
boxing
charConcat
compareIdentical
conditionAssign
constructorName
deadCode
dep-ann
deprecation
discouraged
emptyBlock
enumIdentifier
enumSwitch
fallthrough
fieldHiding
finalBound
finally
forbidden
hashCode
hiding
indirectStatic
intfAnnotation
intfNonInherited
intfRedundant
javadoc
localHiding
maskedCatchBlock
nls
noEffectAssign
null
nullDereference
over-ann
paramAssign
pkgDefaultMethod
raw
semicolon
serial
specialParamHiding
static-access
staticReceiver
super
suppress
synthetic-access
syncOverride
syntheticAccess
tasks(<task1>|...|<taskN>)
typeHiding
unchecked
unnecessaryElse
unqualified-field-access
unqualifiedField
unused
unusedArgument
unusedImport
unusedLabel
unusedLocal
unusedPrivate
unusedThrown
unusedTypeArgs
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
allDeadCode dead code including trivial if(DEBUG) check
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
compareIdentical comparing identical expressions
conditionAssign possible accidental boolean assignment
constructorName method with constructor name
deadCode dead code excluding trivial if (DEBUG) check
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
enumIdentifier occurrence of enum used as identifier
enumSwitch 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
hashCode missing hashCode() method when overriding equals()
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
intfRedundant find redundant superinterfaces
javadoc invalid javadoc
localHiding local variable hiding another variable
maskedCatchBlock hidden catch block
nls non-nls string literals (lacking of tags //$NON-NLS-<n>)
noEffectAssign assignment with no effect
null potential missing or redundant null check
nullDereference missing 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
super overriding a method without making a super invocation
suppress enable @SuppressWarnings
syncOverride missing synchronized in synchronized method override
syntheticAccess 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
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
unusedTypeArgs unused type arguments for method
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.
Annotation processing options (require a 1.6 VM or above and are used only if the compliance is 1.6)
-Akey[=value] Annotation processors options that are passed to annotation processors. key is made of identifiers separated by dots
-proc:[only|none] If -proc:only is specified, the annotation processors will run but no compilation will be performed. If -proc:none is specified, annotation processors will not be discovered or run; compilation will proceed as if no annotation processors were found. By default the compiler must search the classpath for annotation processors, so specifying -proc:none may speed compilation if annotation processing is not required.
-processor <class1[,class2,...]> Qualified class names of annotation processors to run. If specified, the normal processor discovery process will be skipped.
-processorpath <dir 1>;<dir 2>;...;<dir P> A list of directories or jar files which will be searched for annotation processors. Entries are separated by the platform path separator. If not specified, the classpath will be searched instead.
-s <dir> The directory where generated source files will be created.
-XprintProcessorInfo Print information about which annotations and which elements a processor is asked to process
-XprintRounds Print information about annotation processing rounds
-classNames <class1[,class2,...]> Qualified names of binary types that need to be processed
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 buildfile using the javac adapter. In order to use the Eclipse compiler, you simply need to define the build.compiler property in your buildfile.

In order to get the batch compiler working in an ant buildfile, the ant runtime classpath needs to contain the Eclipse batch compiler. When you run your ant buildfile:

  1. outside of Eclipse: the easiest way to set up the ant runtime classpath is to add the ecj.jar file using the -lib argument or dumping it inside the ANT_HOME location.
  2. inside Eclipse using the same JRE than Eclipse: the Eclipse batch compiler is implicitely added to the ant runtime classpath.
  3. inside Eclipse using the different JRE: the Eclipse batch compiler must be explicitely added to the ant runtime classpath. This can be done using the ecj.jar file or using the org.eclipse.jdt.core jar file and the jdtCompilerAdapter.jar file located inside the org.eclipse.jdt.core jar file (this jar file needs to be extracted first).

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 (<compilerarg>) 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>
...

Note:
  1. To prevent compiler dependant buildfiles, we strongly advise you to use a <compilerarg> whose "compiler" attribute value is org.eclipse.jdt.core.JDTCompilerAdapter. If this is not set, the buildfile 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.
  2. <compilerarg> should not be used to set values like target value, source value, debug options, or any options that could be set using the defined attributes of the javac ant task. Its usage must be reserved to pass compiler specific options like warning options. When a command-line argument is specified more than once, the Eclipse batch compiler can report errors like:
    duplicate target compliance setting specification: 1.5

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

 
 
  Published under the terms of the Eclipse Public License Version 1.0 ("EPL") Design by Interspire