1javac(1) General Commands Manual javac(1)
2
3
4
6 javac - Java programming language compiler
7
9 javac [ options ] [ sourcefiles ] [ classes ] [ @argfiles ]
10
11
12
13 Arguments may be in any order.
14
15 options
16 Command-line options.
17
18 sourcefiles
19 One or more source files to be compiled (such as MyClass.java).
20
21 classes
22 One or more classes to be processed for annotations (such as
23 MyPackage.MyClass).
24
25 @argfiles
26 One or more files that lists options and source files. The -J
27 options are not allowed in these files.
28
29
31 The javac tool reads class and interface definitions, written in the
32 Java programming language, and compiles them into bytecode class files.
33 It can also process annotations in Java source files and classes.
34
35 There are two ways to pass source code file names to javac:
36
37 o For a small number of source files, simply list the file names on
38 the command line.
39
40 o For a large number of source files, list the file names in a file,
41 separated by blanks or line breaks. Then use the list file name on
42 the javac command line, preceded by an @ character.
43
44
45 Source code file names must have .java suffixes, class file names must
46 have .class suffixes, and both source and class files must have root
47 names that identify the class. For example, a class called MyClass
48 would be written in a source file called MyClass.java and compiled into
49 a bytecode class file called MyClass.class.
50
51 Inner class definitions produce additional class files. These class
52 files have names combining the inner and outer class names, such as
53 MyClass$MyInnerClass.class.
54
55 You should arrange source files in a directory tree that reflects their
56 package tree. For example, if you keep all your source files in
57 /workspace, the source code for com.mysoft.mypack.MyClass should be in
58 /workspace/com/mysoft/mypack/MyClass.java.
59
60 By default, the compiler puts each class file in the same directory as
61 its source file. You can specify a separate destination directory with
62 -d (see Options, below).
63
65 The compiler has a set of standard options that are supported on the
66 current development environment and will be supported in future
67 releases. An additional set of non-standard options are specific to the
68 current virtual machine and compiler implementations and are subject to
69 change in the future. Non-standard options begin with -X.
70
71 Standard Options
72 -Akey[=value]
73 Options to pass to annotation processors. These are not inter‐
74 preted by javac directly, but are made available for use by indi‐
75 vidual processors. key should be one or more identifiers sepa‐
76 rated by ".".
77
78 -cp path or -classpath path
79 Specify where to find user class files, and (optionally) annota‐
80 tion processors and source files. This class path overrides the
81 user class path in the CLASSPATH environment variable. If neither
82 CLASSPATH, -cp nor -classpath is specified, the user class path
83 consists of the current directory. See Setting the Class Path for
84 more details.
85 >If the -sourcepath option is not specified, the user class path
86 is also searched for source files.
87 If the -processorpath option is not specified, the class path is
88 also searched for annotation processors.
89
90 -Djava.ext.dirs=directories
91 Override the location of installed extensions.
92
93 -Djava.endorsed.dirs=directories
94 Override the location of endorsed standards path.
95
96 -d directory
97 Set the destination directory for class files. The directory must
98 already exist; javac will not create it. If a class is part of a
99 package, javac puts the class file in a subdirectory reflecting
100 the package name, creating directories as needed. For example, if
101 you specify -d /home/myclasses and the class is called
102 com.mypackage.MyClass, then the class file is called
103 /home/myclasses/com/mypackage/MyClass.class.
104 If -d is not specified, javac puts each class files in the same
105 directory as the source file from which it was generated.
106 Note: The directory specified by -d is not automatically added to
107 your user class path.
108
109 -deprecation
110 Show a description of each use or override of a deprecated member
111 or class. Without -deprecation, javac shows a summary of the
112 source files that use or override deprecated members or classes.
113 -deprecation is shorthand for -Xlint:deprecation.
114
115 -encoding encoding
116 Set the source file encoding name, such as EUC-JP and UTF-8. If
117 -encoding is not specified, the platform default converter is
118 used.
119
120 -endorseddirs directories
121 Override the location of endorsed standards path.
122
123 -extdirs directories
124 Overrides the location of the ext directory. The directories
125 variable is a colon-separated list of directories. Each JAR ar‐
126 chive in the specified directories is searched for class files.
127 All JAR archives found are automatically part of the class path.
128 If you are cross-compiling (compiling classes against bootstrap
129 and extension classes of a different Java platform implementa‐
130 tion), this option specifies the directories that contain the
131 extension classes. See Cross-Compilation Options for more infor‐
132 mation.
133
134 -g Generate all debugging information, including local variables. By
135 default, only line number and source file information is gener‐
136 ated.
137
138 -g:none
139 Do not generate any debugging information.
140
141 -g:{keyword list}
142 Generate only some kinds of debugging information, specified by a
143 comma separated list of keywords. Valid keywords are:
144
145 source
146 Source file debugging information
147
148 lines
149 Line number debugging information
150
151 vars
152 Local variable debugging information
153
154 -help
155 Print a synopsis of standard options.
156
157 -implicit:{class,none}
158 Controls the generation of class files for implicitly loaded
159 source files. To automatically generate class files, use
160 -implicit:class. To suppress class file generation, use
161 -implicit:none. If this option is not specified, the default is
162 to automatically generate class files. In this case, the compiler
163 will issue a warning if any such class files are generated when
164 also doing annotation processing. The warning will not be issued
165 if this option is set explicitly. See Searching For Types.
166
167 -Joption
168 Pass option to the java launcher called by javac. For example,
169 -J-Xms48m sets the startup memory to 48 megabytes. It is a common
170 convention for -J to pass options to the underlying VM executing
171 applications written in Java.
172 Note: CLASSPATH, -classpath, -bootclasspath, and -extdirs do not
173 specify the classes used to run javac. Fiddling with the imple‐
174 mentation of the compiler in this way is usually pointless and
175 always risky. If you do need to do this, use the -J option to
176 pass through options to the underlying java launcher.
177
178 -nowarn
179 Disable warning messages. This has the same meaning as
180 -Xlint:none.
181
182 -proc: {none,only}
183 Controls whether annotation processing and/or compilation is
184 done. -proc:none means that compilation takes place without anno‐
185 tation processing. -proc:only means that only annotation process‐
186 ing is done, without any subsequent compilation.
187
188 -processor class1[,class2,class3...]
189 Names of the annotation processors to run. This bypasses the
190 default discovery process.
191
192 -processorpath path
193 Specify where to find annotation processors; if this option is
194 not used, the class path will be searched for processors.
195
196 -s dir
197 Specify the directory where to place generated source files. The
198 directory must already exist; javac will not create it. If a
199 class is part of a package, the compiler puts the source file in
200 a subdirectory reflecting the package name, creating directories
201 as needed. For example, if you specify -s /home/mysrc and the
202 class is called com.mypackage.MyClass, then the source file will
203 be placed in /home/mysrc/com/mypackage/MyClass.java.
204
205 -source release
206 Specifies the version of source code accepted. The following val‐
207 ues for release are allowed:
208
209 1.3
210 The compiler does not support assertions, generics, or other
211 language features introduced after Java SE 1.3.
212
213 1.4
214 The compiler accepts code containing assertions, which were
215 introduced in Java SE 1.4.
216
217 1.5
218 The compiler accepts code containing generics and other lan‐
219 guage features introduced in Java SE 5.
220
221 5 Synonym for 1.5.
222
223 1.6
224 No language changes were introduced in Java SE 6. However,
225 encoding errors in source files are now reported as errors
226 instead of warnings as in previous releases of Java SE.
227
228 6 Synonym for 1.6.
229
230 1.7
231 This is the default value. The compiler accepts code with fea‐
232 tures introduced in Java SE 7.
233
234 7 Synonym for 1.7.
235
236 -sourcepath sourcepath
237 Specify the source code path to search for class or interface
238 definitions. As with the user class path, source path entries are
239 separated by colons (:) and can be directories, JAR archives, or
240 ZIP archives. If packages are used, the local path name within
241 the directory or archive must reflect the package name.
242 Note: Classes found through the class path may be subject to
243 automatic recompilation if their sources are also found. See
244 Searching For Types.
245
246 -verbose
247 Verbose output. This includes information about each class loaded
248 and each source file compiled.
249
250 -version
251 Print version information.
252
253 -Werror
254 Terminate compilation if warnings occur.
255
256 -X Display information about non-standard options and exit.
257
258
259 Cross-Compilation Options
260 By default, classes are compiled against the bootstrap and extension
261 classes of the platform that javac shipped with. But javac also sup‐
262 ports cross-compiling, where classes are compiled against a bootstrap
263 and extension classes of a different Java platform implementation. It
264 is important to use -bootclasspath and -extdirs when cross-compiling;
265 see Cross-Compilation Example below.
266
267 -target version
268 Generate class files that target a specified version of the VM.
269 Class files will run on the specified target and on later ver‐
270 sions, but not on earlier versions of the VM. Valid targets are
271 1.1, 1.2, 1.3, 1.4, 1.5 (also 5), 1.6 (also 6), and 1.7 (also 7).
272
273 The default for -target depends on the value of -source:
274
275 o If -source is not specified, the value of -target is 1.7
276
277 o If -source is 1.2, the value of -target is 1.4
278
279 o If -source is 1.3, the value of -target is 1.4
280
281 o If -source is 1.5, the value of -target is 1.7
282
283 o If -source is 1.6, the value of -target is 1.7
284
285 o For all other values of -source, the value of -target is the
286 value of -source.
287
288 -bootclasspath bootclasspath
289 Cross-compile against the specified set of boot classes. As with
290 the user class path, boot class path entries are separated by
291 colons (:) and can be directories, JAR archives, or ZIP archives.
292
293
294 Non-Standard Options
295 -Xbootclasspath/p:path
296 Prepend to the bootstrap class path.
297
298 -Xbootclasspath/a:path
299 Append to the bootstrap class path.
300
301 -Xbootclasspath/:path
302 Override location of bootstrap class files.
303
304 -Xlint
305 Enable all recommended warnings. In this release, enabling all
306 available warnings is recommended.
307
308 -Xlint:all
309 Enable all recommended warnings. In this release, enabling all
310 available warnings is recommended.
311
312 -Xlint:none
313 Disable all warnings.
314
315 -Xlint:name
316 Enable warning name. See the section Warnings That Can Be Enabled
317 or Disabled with -Xlint Option for a list of warnings you can
318 enable with this option.
319
320 -Xlint:-name
321 Disable warning name. See the section Warnings That Can Be
322 Enabled or Disabled with -Xlint Option for a list of warnings you
323 can disable with this option.
324
325 -Xmaxerrs number
326 Set the maximum number of errors to print.
327
328 -Xmaxwarns number
329 Set the maximum number of warnings to print.
330
331 -Xstdout filename
332 Send compiler messages to the named file. By default, compiler
333 messages go to System.err.
334
335 -Xprefer:{newer,source}
336 Specify which file to read when both a source file and class file
337 are found for a type. (See Searching For Types). If -Xpre‐
338 fer:newer is used, it reads the newer of the source or class file
339 for a type (default). If the -Xprefer:source option is used, it
340 reads source file. Use -Xprefer:source when you want to be sure
341 that any annotation processors can access annotations declared
342 with a retention policy of SOURCE.
343
344 -Xpkginfo:{always,legacy,nonempty}
345 Specify handling of package-info files
346
347 -Xprint
348 Print out textual representation of specified types for debugging
349 purposes; perform neither annotation processing nor compilation.
350 The format of the output may change.
351
352 -XprintProcessorInfo
353 Print information about which annotations a processor is asked to
354 process.
355
356 -XprintRounds
357 Print information about initial and subsequent annotation pro‐
358 cessing rounds.
359
360
361 Warnings That Can Be Enabled or Disabled with -Xlint Option
362 Enable warning name with the option -Xlint:name, where name is one of
363 the following warning names. Similarly, you can disable warning name
364 with the option -Xlint:-name:
365
366 cast
367 Warn about unnecessary and redundant casts. For example:
368 String s = (String)"Hello!"
369
370 classfile
371 Warn about issues related to classfile contents.
372
373 deprecation
374 Warn about use of deprecated items. For example:
375 java.util.Date myDate = new java.util.Date();
376 int currentDay = myDate.getDay();
377 The method java.util.Date.getDay has been deprecated since JDK
378 1.1.
379
380 dep-ann
381 Warn about items that are documented with an @deprecated Javadoc
382 comment, but do not have a @Deprecated annotation. For example:
383 /**
384 * @deprecated As of Java SE 7, replaced by {@link #newMethod()}
385 */
386
387 public static void deprecatedMethood() { }
388
389 public static void newMethod() { }
390
391 divzero
392 Warn about division by constant integer 0. For example:
393 int divideByZero = 42 / 0;
394
395 empty
396 Warn about empty statements after if statements. For example:
397 class E {
398 void m() {
399 if (true) ;
400 }
401 }
402
403 fallthrough
404 Check switch blocks for fall-through cases and provide a warning
405 message for any that are found. Fall-through cases are cases in a
406 switch block, other than the last case in the block, whose code
407 does not include a break statement, allowing code execution to
408 "fall through" from that case to the next case. For example, the
409 code following the case 1 label in this switch block does not end
410 with a break statement:
411 switch (x) {
412 case 1:
413 System.out.println("1");
414 // No break statement here.
415 case 2:
416 System.out.println("2");
417 }
418 If the -Xlint:fallthrough flag were used when compiling this
419 code, the compiler would emit a warning about "possible
420 fall-through into case," along with the line number of the case
421 in question.
422
423 finally
424 Warn about finally clauses that cannot complete normally. For
425 example:
426 public static int m() {
427 try {
428 throw new NullPointerException();
429 } catch (NullPointerException e) {
430 System.err.println("Caught NullPointerException.");
431 return 1;
432 } finally {
433 return 0;
434 }
435 }
436 The compiler generates a warning for finally block in this exam‐
437 ple. When this method is called, it returns a value of 0, not 1.
438 A finally block always executes when the try block exits. In this
439 example, if control is transferred to the catch, then the method
440 exits. However, the finally block must be executed, so it is exe‐
441 cuted, even though control has already been transferred outside
442 the method.
443
444 options
445 Warn about issues relating to the use of command line options.
446 See Cross-Compilation Example for an example of this kind of
447 warning.
448
449 overrides
450 Warn about issues regarding method overrides. For example, con‐
451 sider the following two classes:
452 public class ClassWithVarargsMethod {
453 void varargsMethod(String... s) { }
454 }
455 public class ClassWithOverridingMethod extends ClassWithVarargsMethod {
456 @Override
457 void varargsMethod(String[] s) { }
458 }
459 The compiler generates a warning similar to the following:
460 warning: [override] varargsMethod(String[]) in ClassWithOverrid‐
461 ingMethod overrides varargsMethod(String...) in ClassWith‐
462 VarargsMethod; overriding method is missing '...'
463 When the compiler encounters a varargs method, it translates the
464 varargs formal parameter into an array. In the method ClassWith‐
465 VarargsMethod.varargsMethod, the compiler translates the varargs
466 formal parameter String... s to the formal parameter String[] s,
467 an array, which matches the formal parameter of the method Class‐
468 WithOverridingMethod.varargsMethod. Consequently, this example
469 compiles.
470
471 path
472 Warn about invalid path elements and nonexistent path directories
473 on the command line (with regards to the class path, the source
474 path, and other paths). Such warnings cannot be suppressed with
475 the @SuppressWarnings annotation. For example:
476 javac -Xlint:path -classpath /nonexistentpath Example.java
477
478 processing
479 Warn about issues regarding annotation processing. The compiler
480 generates this warning if you have a class that has an annota‐
481 tion, and you use an annotation processor that cannot handle that
482 type of exception. For example, the following is a simple annota‐
483 tion processor:
484 Source file AnnoProc.java:
485 import java.util.*;
486 import javax.annotation.processing.*;
487 import javax.lang.model.*;
488 import javax.lang.model.element.*;
489
490 @SupportedAnnotationTypes("NotAnno")
491 public class AnnoProc extends AbstractProcessor {
492 public boolean process(Set<? extends TypeElement> elems, RoundEnvironment renv) {
493 return true;
494 }
495
496 public SourceVersion getSupportedSourceVersion() {
497 return SourceVersion.latest();
498 }
499 }
500 Source file AnnosWithoutProcessors.java:
501 @interface Anno { }
502
503 @Anno
504 class AnnosWithoutProcessors { }
505 The following commands compile the annotation processor AnnoProc,
506 then run this annotation processor against the source file
507 AnnosWithoutProcessors.java:
508 % javac AnnoProc.java
509 % javac -cp . -Xlint:processing -processor AnnoProc -proc:only AnnosWithoutProcessors.java
510 When the compiler runs the annotation processor against the
511 source file AnnosWithoutProcessors.java, it generates the follow‐
512 ing warning:
513 warning: [processing] No processor claimed any of these annota‐
514 tions: Anno
515 To resolve this issue, you can rename the annotation defined and
516 used in the class AnnosWithoutProcessors from Anno to NotAnno.
517
518 rawtypes
519 Warn about unchecked operations on raw types. The following
520 statement generates a rawtypes warning:
521 void countElements(List l) { ... }
522 The following does not generate a rawtypes warning:
523 void countElements(List<?> l) { ... }
524 List is a raw type. However, List<?> is a unbounded wildcard
525 parameterized type. Because List is a parameterized interface,
526 you should always specify its type argument. In this example, the
527 List formal argument is specified with a unbounded wildcard (?)
528 as its formal type parameter, which means that the countElements
529 method can accept any instantiation of the List interface.
530
531 serial
532 Warn about missing serialVersionUID definitions on serializable
533 classes. For example:
534 public class PersistentTime implements Serializable
535 {
536 private Date time;
537
538 public PersistentTime() {
539 time = Calendar.getInstance().getTime();
540 }
541
542 public Date getTime() {
543 return time;
544 }
545 }
546 The compiler generates the following warning:
547 warning: [serial] serializable class PersistentTime has no defi‐
548 nition of serialVersionUID
549 If a serializable class does not explicitly declare a field named
550 serialVersionUID, then the serialization runtime will calculate a
551 default serialVersionUID value for that class based on various
552 aspects of the class, as described in the Java Object Serializa‐
553 tion Specification. However, it is strongly recommended that all
554 serializable classes explicitly declare serialVersionUID values
555 because the default process of computing serialVersionUID vales
556 is highly sensitive to class details that may vary depending on
557 compiler implementations, and can thus result in unexpected
558 InvalidClassExceptions during deserialization. Therefore, to
559 guarantee a consistent serialVersionUID value across different
560 Java compiler implementations, a serializable class must declare
561 an explicit serialVersionUID value.
562
563 static
564 Warn about issues relating to use of statics. For example:
565 class XLintStatic {
566 static void m1() { }
567 void m2() { this.m1(); }
568 }
569 The compiler generates the following warning:
570 warning: [static] static method should be qualified by type name, XLintStatic, instead of by an expression
571 To resolve this issue, you can call the static method m1 as fol‐
572 lows:
573 XLintStatic.m1();
574 Alternatively, you can remove the static keyword from the decla‐
575 ration of the method m1.
576
577 try
578 Warn about issues relating to use of try blocks, including
579 try-with-resources statements. For example, a warning is gener‐
580 ated for the following statement because the resource ac declared
581 in the try statement is not used:
582 try ( AutoCloseable ac = getResource() ) {
583 // do nothing
584 }
585
586 unchecked
587 Give more detail for unchecked conversion warnings that are man‐
588 dated by the Java Language Specification. For example:
589 List l = new ArrayList<Number>();
590 List<String> ls = l; // unchecked warning
591 During type erasure, the types ArrayList<Number> and List<String>
592 become ArrayList and List, respectively.
593 The variable ls has the parameterized type List<String>. When the
594 List referenced by l is assigned to ls, the compiler generates an
595 unchecked warning; the compiler is unable to determine at compile
596 time, and moreover knows that the JVM will not be able to deter‐
597 mine at runtime, if l refers to a List<String> type; it does not.
598 Consequently, heap pollution occurs.
599 In detail, a heap pollution situation occurs when the List object
600 l, whose static type is List<Number>, is assigned to another List
601 object, ls, that has a different static type, List<String>. How‐
602 ever, the compiler still allows this assignment. It must allow
603 this assignment to preserve backwards compatibility with versions
604 of Java SE that do not support generics. Because of type erasure,
605 List<Number> and List<String> both become List. Consequently, the
606 compiler allows the assignment of the object l, which has a raw
607 type of List, to the object ls.
608
609 varargs
610 Warn about unsafe usages of variable arguments (varargs) methods,
611 in particular, those that contain non-reifiable arguments. For
612 example:
613 public class ArrayBuilder {
614 public static <T> void addToList (List<T> listArg, T... elements) {
615 for (T x : elements) {
616 listArg.add(x);
617 }
618 }
619 }
620 The compiler generates the following warning for the definition
621 of the method ArrayBuilder.addToList:
622 warning: [varargs] Possible heap pollution from parameterized vararg type T
623 When the compiler encounters a varargs method, it translates the
624 varargs formal parameter into an array. However, the Java pro‐
625 gramming language does not permit the creation of arrays of
626 parameterized types. In the method ArrayBuilder.addToList, the
627 compiler translates the varargs formal parameter T... elements to
628 the formal parameter T[] elements, an array. However, because of
629 type erasure, the compiler converts the varargs formal parameter
630 to Object[] elements. Consequently, there is a possibility of
631 heap pollution.
632
633
635 To shorten or simplify the javac command line, you can specify one or
636 more files that themselves contain arguments to the javac command
637 (except -J options). This enables you to create javac commands of any
638 length on any operating system.
639
640 An argument file can include javac options and source filenames in any
641 combination. The arguments within a file can be space-separated or new‐
642 line-separated. If a filename contains embedded spaces, put the whole
643 filename in double quotes.
644
645 Filenames within an argument file are relative to the current direc‐
646 tory, not the location of the argument file. Wildcards (*) are not
647 allowed in these lists (such as for specifying *.java). Use of the '@'
648 character to recursively interpret files is not supported. The -J
649 options are not supported because they are passed to the launcher,
650 which does not support argument files.
651
652 When executing javac, pass in the path and name of each argument file
653 with the '@' leading character. When javac encounters an argument
654 beginning with the character `@', it expands the contents of that file
655 into the argument list.
656
657 Example - Single Arg File
658 You could use a single argument file named "argfile" to hold all javac
659 arguments:
660
661 % javac @argfile
662
663
664 This argument file could contain the contents of both files shown in
665 the next example.
666
667 Example - Two Arg Files
668 You can create two argument files -- one for the javac options and the
669 other for the source filenames: (Notice the following lists have no
670 line-continuation characters.)
671
672 Create a file named "options" containing:
673
674 -d classes
675 -g
676 -sourcepath /java/pubs/ws/1.3/src/share/classes
677
678
679
680 Create a file named "classes" containing:
681
682 MyClass1.java
683 MyClass2.java
684 MyClass3.java
685
686
687
688 You would then run javac with:
689
690 % javac @options @classes
691
692
693
694 Example - Arg Files with Paths
695 The argument files can have paths, but any filenames inside the files
696 are relative to the current working directory (not path1 or path2):
697
698 % javac @path1/options @path2/classes
699
700
702 javac provides direct support for annotation processing, superseding
703 the need for the separate annotation processing tool, apt.
704
705 The API for annotation processors is defined in the javax.annota‐
706 tion.processing and javax.lang.model packages and subpackages.
707
708 Overview of annotation processing
709 Unless annotation processing is disabled with the -proc:none option,
710 the compiler searches for any annotation processors that are available.
711 The search path can be specified with the -processorpath option; if it
712 is not given, the user class path is used. Processors are located by
713 means of service provider-configuration files named META-INF/ser‐
714 vices/javax.annotation.processing.Processor on the search path. Such
715 files should contain the names of any annotation processors to be used,
716 listed one per line. Alternatively, processors can be specified explic‐
717 itly, using the -processor option.
718
719 After scanning the source files and classes on the command line to
720 determine what annotations are present, the compiler queries the pro‐
721 cessors to determine what annotations they process. When a match is
722 found, the processor will be invoked. A processor may "claim" the anno‐
723 tations it processes, in which case no further attempt is made to find
724 any processors for those annotations. Once all annotations have been
725 claimed, the compiler does not look for additional processors.
726
727 If any processors generate any new source files, another round of anno‐
728 tation processing will occur: any newly generated source files will be
729 scanned, and the annotations processed as before. Any processors
730 invoked on previous rounds will also be invoked on all subsequent
731 rounds. This continues until no new source files are generated.
732
733 After a round occurs where no new source files are generated, the anno‐
734 tation processors will be invoked one last time, to give them a chance
735 to complete any work they may need to do. Finally, unless the
736 -proc:only option is used, the compiler will compile the original and
737 all the generated source files.
738
739 Implicitly loaded source files
740 To compile a set of source files, the compiler may need to implicitly
741 load additional source files. (See Searching For Types). Such files are
742 currently not subject to annotation processing. By default, the com‐
743 piler will give a warning if annotation processing has occurred and any
744 implicitly loaded source files are compiled. See the -implicit option
745 for ways to suppress the warning.
746
748 When compiling a source file, the compiler often needs information
749 about a type whose definition did not appear in the source files given
750 on the command line. The compiler needs type information for every
751 class or interface used, extended, or implemented in the source file.
752 This includes classes and interfaces not explicitly mentioned in the
753 source file but which provide information through inheritance.
754
755 For example, when you subclass java.applet.Applet, you are also using
756 Applet's ancestor classes: java.awt.Panel, java.awt.Container,
757 java.awt.Component, and java.lang.Object.
758
759 When the compiler needs type information, it looks for a source file or
760 class file which defines the type. The compiler searches for class
761 files first in the bootstrap and extension classes, then in the user
762 class path (which by default is the current directory). The user class
763 path is defined by setting the CLASSPATH environment variable or by
764 using the -classpath command line option. (For details, see Setting the
765 Class Path).
766
767 If you set the -sourcepath option, the compiler searches the indicated
768 path for source files; otherwise the compiler searches the user class
769 path for both class files and source files.
770
771 You can specify different bootstrap or extension classes with the
772 -bootclasspath and -extdirs options; see Cross-Compilation Options
773 below.
774
775 A successful type search may produce a class file, a source file, or
776 both. If both are found, you can use the -Xprefer option to instruct
777 the compiler which to use. If newer is given, the compiler will use the
778 newer of the two files. If source is given, it will use the source
779 file. The default is newer.
780
781 If a type search finds a source file for a required type, either by
782 itself, or as a result of the setting for -Xprefer, the compiler will
783 read the source file to get the information it needs. In addition, it
784 will by default compile the source file as well. You can use the
785 -implicit option to specify the behavior. If none is given, no class
786 files will be generated for the source file. If class is given, class
787 files will be generated for the source file.
788
789 The compiler may not discover the need for some type information until
790 after annotation processing is complete. If the type information is
791 found in a source file and no -implicit option is given, the compiler
792 will give a warning that the file is being compiled without being sub‐
793 ject to annotation processing. To disable the warning, either specify
794 the file on the command line (so that it will be subject to annotation
795 processing) or use the -implicit option to specify whether or not class
796 files should be generated for such source files.
797
799 javac supports the new Java Compiler API defined by the classes and
800 interfaces in the javax.tools package.
801
802 Example
803 To perform a compilation using arguments as you would give on the com‐
804 mand line, you can use the following:
805
806 JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
807 int rc = javac.run(null, null, null, args);
808
809
810 This will write any diagnostics to the standard output stream, and
811 return the exit code that javac would give when invoked from the com‐
812 mand line.
813
814 You can use other methods on the javax.tools.JavaCompiler interface to
815 handle diagnostics, control where files are read from and written to,
816 and so on.
817
818 Old Interface
819 Note: This API is retained for backwards compatibility only; all new
820 code should use the Java Compiler API, described above.
821
822 The com.sun.tools.javac.Main class provides two static methods to
823 invoke the compiler from a program:
824
825 public static int compile(String[] args);
826 public static int compile(String[] args, PrintWriter out);
827
828
829 The args parameter represents any of the command line arguments that
830 would normally be passed to the javac program and are outlined in the
831 above Synopsis section.
832
833 The out parameter indicates where the compiler's diagnostic output is
834 directed.
835
836 The return value is equivalent to the exit value from javac.
837
838 Note that all other classes and methods found in a package whose name
839 starts with com.sun.tools.javac (informally known as sub-packages of
840 com.sun.tools.javac) are strictly internal and subject to change at any
841 time.
842
844 Compiling a Simple Program
845 One source file, Hello.java, defines a class called greetings.Hello.
846 The greetings directory is the package directory both for the source
847 file and the class file and is off the current directory. This allows
848 us to use the default user class path. It also makes it unnecessary to
849 specify a separate destination directory with -d.
850
851 % ls
852 greetings/
853 % ls greetings
854 Hello.java
855 % cat greetings/Hello.java
856 package greetings;
857
858 public class Hello {
859 public static void main(String[] args) {
860 for (int i=0; i < args.length; i++) {
861 System.out.println("Hello " + args[i]);
862 }
863 }
864 }
865 % javac greetings/Hello.java
866 % ls greetings
867 Hello.class Hello.java
868 % java greetings.Hello World Universe Everyone
869 Hello World
870 Hello Universe
871 Hello Everyone
872
873
874 Compiling Multiple Source Files
875 This example compiles all the source files in the package greetings.
876
877 % ls
878 greetings/
879 % ls greetings
880 Aloha.java GutenTag.java Hello.java Hi.java
881 % javac greetings/*.java
882 % ls greetings
883 Aloha.class GutenTag.class Hello.class Hi.class
884 Aloha.java GutenTag.java Hello.java Hi.java
885
886
887 Specifying a User Class Path
888 Having changed one of the source files in the previous example, we
889 recompile it:
890
891 % pwd
892 /examples
893 % javac greetings/Hi.java
894
895
896 Since greetings.Hi refers to other classes in the greetings package,
897 the compiler needs to find these other classes. The example above
898 works, because our default user class path happens to be the directory
899 containing the package directory. But suppose we want to recompile this
900 file and not worry about which directory we're in? Then we need to add
901 /examples to the user class path. We can do this by setting CLASSPATH,
902 but here we'll use the -classpath option.
903
904 % javac -classpath /examples /examples/greetings/Hi.java
905
906
907 If we change greetings.Hi again, to use a banner utility, that utility
908 also needs to be accessible through the user class path.
909
910 % javac -classpath /examples:/lib/Banners.jar \
911 /examples/greetings/Hi.java
912
913
914 To execute a class in greetings, we need access both to greetings and
915 to the classes it uses.
916
917 % java -classpath /examples:/lib/Banners.jar greetings.Hi
918
919
920 Separating Source Files and Class Files
921 It often makes sense to keep source files and class files in separate
922 directories, especially on large projects. We use -d to indicate the
923 separate class file destination. Since the source files are not in the
924 user class path, we use -sourcepath to help the compiler find them.
925
926 % ls
927 classes/ lib/ src/
928 % ls src
929 farewells/
930 % ls src/farewells
931 Base.java GoodBye.java
932 % ls lib
933 Banners.jar
934 % ls classes
935 % javac -sourcepath src -classpath classes:lib/Banners.jar \
936 src/farewells/GoodBye.java -d classes
937 % ls classes
938 farewells/
939 % ls classes/farewells
940 Base.class GoodBye.class
941
942
943 Note: The compiler compiled src/farewells/Base.java, even though we
944 didn't specify it on the command line. To trace automatic compiles, use
945 the -verbose option.
946
947 Cross-Compilation Example
948 The following example uses javac to compile code that will run on a 1.6
949 VM.
950
951 % javac -source 1.6 -target 1.6 -bootclasspath jdk1.6.0/lib/rt.jar \
952 -extdirs "" OldCode.java
953
954
955 The -source 1.6 option specifies that version 1.6 (or 6) of the Java
956 programming language be used to compile OldCode.java. The option -tar‐
957 get 1.6 option ensures that the generated class files will be compati‐
958 ble with 1.6 VMs. Note that in most cases, the value of the -target
959 option is the value of the -source option; in this example, you can
960 omit the -target option.
961
962 You must specify the -bootclasspath option to specify the correct ver‐
963 sion of the bootstrap classes (the rt.jar library). If not, the com‐
964 piler generates a warning:
965
966 % javac -source 1.6 OldCode.java
967 warning: [options] bootstrap class path not set in conjunction with -source 1.6
968
969
970 If you do not specify the correct version of bootstrap classes, the
971 compiler will use the old language rules (in this example, it will use
972 version 1.6 of the Java programming language) combined with the new
973 bootstrap classes, which can result in class files that do not work on
974 the older platform (in this case, Java SE 6) because reference to
975 non-existent methods can get included.
976
978 o The javac Guide @
979 http://docs.oracle.com/javase/7/docs/tech‐
980 notes/guides/javac/index.html
981
982 o java(1) - the Java Application Launcher
983
984 o jdb(1) - Java Application Debugger
985
986 o javah(1) - C Header and Stub File Generator
987
988 o javap(1) - Class File Disassembler
989
990 o javadoc(1) - API Documentation Generator
991
992 o jar(1) - JAR Archive Tool
993
994 o The Java Extensions Framework @
995 http://docs.oracle.com/javase/7/docs/technotes/guides/exten‐
996 sions/index.html
997
998
999 16 Mar 2012 javac(1)