KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > javax > tools > JavaCompiler


1 /*
2  * @(#)JavaCompiler.java 1.15 06/09/25
3  *
4  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 package javax.tools;
9
10 import java.io.File JavaDoc;
11 import java.io.InputStream JavaDoc;
12 import java.io.Writer JavaDoc;
13 import java.nio.charset.Charset JavaDoc;
14 import java.util.List JavaDoc;
15 import java.util.Locale JavaDoc;
16 import java.util.concurrent.Callable JavaDoc;
17 import javax.annotation.processing.Processor;
18
19 /**
20  * Interface to invoke Java™ programming language compilers from
21  * programs.
22  *
23  * <p>The compiler might generate diagnostics during compilation (for
24  * example, error messages). If a diagnostic listener is provided,
25  * the diagnostics will be supplied to the listener. If no listener
26  * is provided, the diagnostics will be formatted in an unspecified
27  * format and written to the default output, which is {@code
28  * System.err} unless otherwise specified. Even if a diagnostic
29  * listener is supplied, some diagnostics might not fit in a {@code
30  * Diagnostic} and will be written to the default output.
31  *
32  * <p>A compiler tool has an associated standard file manager, which
33  * is the file manager that is native to the tool (or built-in). The
34  * standard file manager can be obtained by calling {@linkplain
35  * #getStandardFileManager getStandardFileManager}.
36  *
37  * <p>A compiler tool must function with any file manager as long as
38  * any additional requirements as detailed in the methods below are
39  * met. If no file manager is provided, the compiler tool will use a
40  * standard file manager such as the one returned by {@linkplain
41  * #getStandardFileManager getStandardFileManager}.
42  *
43  * <p>An instance implementing this interface must conform to the Java
44  * Language Specification and generate class files conforming to the
45  * Java Virtual Machine specification. The versions of these
46  * specifications are defined in the {@linkplain Tool} interface.
47  *
48  * Additionally, an instance of this interface supporting {@link
49  * javax.lang.model.SourceVersion#RELEASE_6 SourceVersion.RELEASE_6}
50  * or higher must also support {@linkplain javax.annotation.processing
51  * annotation processing}.
52  *
53  * <p>The compiler relies on two services: {@linkplain
54  * DiagnosticListener diagnostic listener} and {@linkplain
55  * JavaFileManager file manager}. Although most classes and
56  * interfaces in this package defines an API for compilers (and
57  * tools in general) the interfaces {@linkplain DiagnosticListener},
58  * {@linkplain JavaFileManager}, {@linkplain FileObject}, and
59  * {@linkplain JavaFileObject} are not intended to be used in
60  * applications. Instead these interfaces are intended to be
61  * implemented and used to provide customized services for a
62  * compiler and thus defines an SPI for compilers.
63  *
64  * <p>There are a number of classes and interfaces in this package
65  * which are designed to ease the implementation of the SPI to
66  * customize the behavior of a compiler:
67  *
68  * <dl>
69  * <dt>{@link StandardJavaFileManager}</dt>
70  * <dd>
71  *
72  * Every compiler which implements this interface provides a
73  * standard file manager for operating on regular {@linkplain
74  * java.io.File files}. The StandardJavaFileManager interface
75  * defines additional methods for creating file objects from
76  * regular files.
77  *
78  * <p>The standard file manager serves two purposes:
79  *
80  * <ul>
81  * <li>basic building block for customizing how a compiler reads
82  * and writes files</li>
83  * <li>sharing between multiple compilation tasks</li>
84  * </ul>
85  *
86  * <p>Reusing a file manager can potentially reduce overhead of
87  * scanning the file system and reading jar files. Although there
88  * might be no reduction in overhead, a standard file manager must
89  * work with multiple sequential compilations making the following
90  * example a recommended coding pattern:
91  *
92  * <pre>
93  * Files[] files1 = ... ; // input for first compilation task
94  * Files[] files2 = ... ; // input for second compilation task
95  *
96  * JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
97  * StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
98  *
99  * {@code Iterable<? extends JavaFileObject>} compilationUnits1 =
100  * fileManager.getJavaFileObjectsFromFiles({@linkplain java.util.Arrays#asList Arrays.asList}(files1));
101  * compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call();
102  *
103  * {@code Iterable<? extends JavaFileObject>} compilationUnits2 =
104  * fileManager.getJavaFileObjects(files2); // use alternative method
105  * // reuse the same file manager to allow caching of jar files
106  * compiler.getTask(null, fileManager, null, null, null, compilationUnits2).call();
107  *
108  * fileManager.close();</pre>
109  *
110  * </dd>
111  *
112  * <dt>{@link DiagnosticCollector}</dt>
113  * <dd>
114  * Used to collect diagnostics in a list, for example:
115  * <pre>
116  * {@code Iterable<? extends JavaFileObject>} compilationUnits = ...;
117  * JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
118  * {@code DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();}
119  * StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
120  * compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits).call();
121  *
122  * for (Diagnostic diagnostic : diagnostics.getDiagnostics())
123  * System.out.format("Error on line %d in %d%n",
124  * diagnostic.getLineNumber()
125  * diagnostic.getSource().toUri());
126  *
127  * fileManager.close();</pre>
128  * </dd>
129  *
130  * <dt>
131  * {@link ForwardingJavaFileManager}, {@link ForwardingFileObject}, and
132  * {@link ForwardingJavaFileObject}
133  * </dt>
134  * <dd>
135  *
136  * Subclassing is not available for overriding the behavior of a
137  * standard file manager as it is created by calling a method on a
138  * compiler, not by invoking a constructor. Instead forwarding
139  * (or delegation) should be used. These classes makes it easy to
140  * forward most calls to a given file manager or file object while
141  * allowing customizing behavior. For example, consider how to
142  * log all calls to {@linkplain JavaFileManager#flush}:
143  *
144  * <pre>
145  * final {@linkplain java.util.logging.Logger Logger} logger = ...;
146  * {@code Iterable<? extends JavaFileObject>} compilationUnits = ...;
147  * JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
148  * StandardJavaFileManager stdFileManager = compiler.getStandardFileManager(null, null, null);
149  * JavaFileManager fileManager = new ForwardingJavaFileManager(stdFileManager) {
150  * public void flush() {
151  * logger.entering(StandardJavaFileManager.class.getName(), "flush");
152  * super.flush();
153  * logger.exiting(StandardJavaFileManager.class.getName(), "flush");
154  * }
155  * };
156  * compiler.getTask(null, fileManager, null, null, null, compilationUnits).call();</pre>
157  * </dd>
158  *
159  * <dt>{@link SimpleJavaFileObject}</dt>
160  * <dd>
161  *
162  * This class provides a basic file object implementation which
163  * can be used as building block for creating file objects. For
164  * example, here is how to define a file object which represent
165  * source code stored in a string:
166  *
167  * <pre>
168  * /**
169  * * A file object used to represent source coming from a string.
170  * {@code *}/
171  * public class JavaSourceFromString extends SimpleJavaFileObject {
172  * /**
173  * * The source code of this "file".
174  * {@code *}/
175  * final String code;
176  *
177  * /**
178  * * Constructs a new JavaSourceFromString.
179  * * {@code @}param name the name of the compilation unit represented by this file object
180  * * {@code @}param code the source code for the compilation unit represented by this file object
181  * {@code *}/
182  * JavaSourceFromString(String name, String code) {
183  * super({@linkplain java.net.URI#create URI.create}("string:///" + name.replace('.','/') + Kind.SOURCE.extension),
184  * Kind.SOURCE);
185  * this.code = code;
186  * }
187  *
188  * {@code @}Override
189  * public CharSequence getCharContent(boolean ignoreEncodingErrors) {
190  * return code;
191  * }
192  * }</pre>
193  * </dd>
194  * </dl>
195  *
196  * @author Peter von der Ah&eacute;
197  * @author Jonathan Gibbons
198  * @see DiagnosticListener
199  * @see Diagnostic
200  * @see JavaFileManager
201  * @since 1.6
202  */

203 public interface JavaCompiler extends Tool, OptionChecker {
204
205     /**
206      * Creates a future for a compilation task with the given
207      * components and arguments. The compilation might not have
208      * completed as described in the CompilationTask interface.
209      *
210      * <p>If a file manager is provided, it must be able to handle all
211      * locations defined in {@link StandardLocation}.
212      *
213      * @param out a Writer for additional output from the compiler;
214      * use {@code System.err} if {@code null}
215      * @param fileManager a file manager; if {@code null} use the
216      * compiler's standard filemanager
217      * @param diagnosticListener a diagnostic listener; if {@code
218      * null} use the compiler's default method for reporting
219      * diagnostics
220      * @param options compiler options, {@code null} means no options
221      * @param classes class names (for annotation processing), {@code
222      * null} means no class names
223      * @param compilationUnits the compilation units to compile, {@code
224      * null} means no compilation units
225      * @return an object representing the compilation
226      * @throws RuntimeException if an unrecoverable error
227      * occurred in a user supplied component. The
228      * {@linkplain Throwable#getCause() cause} will be the error in
229      * user code.
230      * @throws IllegalArgumentException if any of the given
231      * compilation units are of other kind than
232      * {@linkplain JavaFileObject.Kind#SOURCE source}
233      */

234     CompilationTask getTask(Writer JavaDoc out,
235                             JavaFileManager fileManager,
236                             DiagnosticListener<? super JavaFileObject> diagnosticListener,
237                             Iterable JavaDoc<String JavaDoc> options,
238                             Iterable JavaDoc<String JavaDoc> classes,
239                             Iterable JavaDoc<? extends JavaFileObject> compilationUnits);
240
241     /**
242      * Gets a new instance of the standard file manager implementation
243      * for this tool. The file manager will use the given diagnostic
244      * listener for producing any non-fatal diagnostics. Fatal errors
245      * will be signalled with the appropriate exceptions.
246      *
247      * <p>The standard file manager will be automatically reopened if
248      * it is accessed after calls to {@code flush} or {@code close}.
249      * The standard file manager must be usable with other tools.
250      *
251      * @param diagnosticListener a diagnostic listener for non-fatal
252      * diagnostics; if {@code null} use the compiler's default method
253      * for reporting diagnostics
254      * @param locale the locale to apply when formatting diagnostics;
255      * {@code null} means the {@linkplain Locale#getDefault() default locale}.
256      * @param charset the character set used for decoding bytes; if
257      * {@code null} use the platform default
258      * @return the standard file manager
259      */

260     StandardJavaFileManager getStandardFileManager(
261         DiagnosticListener<? super JavaFileObject> diagnosticListener,
262         Locale JavaDoc locale,
263         Charset JavaDoc charset);
264
265     /**
266      * Interface representing a future for a compilation task. The
267      * compilation task has not yet started. To start the task, call
268      * the {@linkplain #call call} method.
269      *
270      * <p>Before calling the call method, additional aspects of the
271      * task can be configured, for example, by calling the
272      * {@linkplain #setProcessors setProcessors} method.
273      */

274     interface CompilationTask extends Callable JavaDoc<Boolean JavaDoc> {
275
276         /**
277          * Sets processors (for annotation processing). This will
278          * bypass the normal discovery mechanism.
279          *
280          * @param processors processors (for annotation processing)
281          * @throws IllegalStateException if the task has started
282          */

283         void setProcessors(Iterable JavaDoc<? extends Processor> processors);
284
285         /**
286          * Set the locale to be applied when formatting diagnostics and
287          * other localized data.
288          *
289          * @param locale the locale to apply; {@code null} means apply no
290          * locale
291          * @throws IllegalStateException if the task has started
292          */

293         void setLocale(Locale JavaDoc locale);
294
295         /**
296          * Performs this compilation task. The compilation may only
297          * be performed once. Subsequent calls to this method throw
298          * IllegalStateException.
299          *
300          * @return true if and only all the files compiled without errors;
301          * false otherwise
302          *
303          * @throws RuntimeException if an unrecoverable error occurred
304          * in a user-supplied component. The
305          * {@linkplain Throwable#getCause() cause} will be the error
306          * in user code.
307          * @throws IllegalStateException if called more than once
308          */

309         Boolean JavaDoc call();
310     }
311 }
312
Popular Tags